MVC Binding to checkbox

后端 未结 2 1063
一生所求
一生所求 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: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++) { %>
        
    <%= Html.HiddenFor(x => x.CheckBoxes[i].Id) %> <%= Html.CheckBoxFor(x => x.CheckBoxes[i].IsSelected) %>
    <% } %>

    which will successfully bind to:

    [HttpPost]
    public ActionResult MyAction(MyViewModel model) 
    {
        // model.CheckBoxes will contain everything you need here
        ...
    }
    

提交回复
热议问题