MVC Binding to checkbox

后端 未结 2 1066
一生所求
一生所求 2020-12-14 12:00

I have found so many questions about this, but none of them go over or seem to go over my scenario. I have a model:

public class CheckBoxModel
{
                     


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-14 12:32

    An alternative to Darin's fantastic answer

    I definitely recommend following Darin's approach for returning classes which will be most of the time. This alternative is a 'quick' and dirty hack if all you need is the checked Ids:

    <% foreach (var cb in Model.CheckBoxes) { %>
      
    name="ids" />
    <% } %>

    Will bind to the int[] ids parameter in the following action:

    [HttpPost]
    public ActionResult MyAction(int[] ids) 
    {
        // ids contains only those ids that were selected
        ...
    }
    
    • The benefit is cleaner html as there is no hidden input.
    • The cost is writing more code in the view.

    In MVC 4.0 (Razor 2.0) you can use the following syntax in your view:

    
    

提交回复
热议问题