MVC Binding to checkbox

后端 未结 2 1061
一生所求
一生所求 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) { %>
      <div>
        <input type="checkbox" 
          value="<%= cb.Id %>"
          <%= cb.IsSelected ? "checked=\"checked\"" : "" %>
          name="ids" />
      </div>
    <% } %>
    

    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:

    <input type="checkbox" value="@cb.Id" checked="@cb.IsSelected" name="ids" />
    
    0 讨论(0)
  • 2020-12-14 12:37

    Try like this:

    <%= Html.CheckBoxFor(x => x.IsSelected) %>
    

    Also if you want to pass along the id don't forget to do so:

    <%= Html.HiddenFor(x => x.Id) %>
    

    And if you had a collection of those:

    public class MyViewModel
    {
        public CheckBoxModel[] CheckBoxes { get; set; }
    }
    

    you could:

    <% for (var i = 0; i < Model.CheckBoxes.Length; i++) { %>
        <div>
            <%= Html.HiddenFor(x => x.CheckBoxes[i].Id) %>
            <%= Html.CheckBoxFor(x => x.CheckBoxes[i].IsSelected) %>
        </div>
    <% } %>
    

    which will successfully bind to:

    [HttpPost]
    public ActionResult MyAction(MyViewModel model) 
    {
        // model.CheckBoxes will contain everything you need here
        ...
    }
    
    0 讨论(0)
提交回复
热议问题