简体   繁体   中英

CheckBox lists in ASP.NET MVC and bind it back to controller

 Html.CheckBox("SelectedStudents", false, new { @class = "check-item", id = x.Id, value = x.Id })

which produce

<input checked="checked" class="check-item" id="4507" name="SelectedStudents" value="4507" type="checkbox">

<input checked="checked" class="check-item" id="4507" name="SelectedStudents" value="4508" type="checkbox">

<input checked="checked" class="check-item" id="4507" name="SelectedStudents" value="4509" type="checkbox">

In mvc model I have

public IEnumerable<string> SelectedStudents { get; set; }

but when I post back, SelectedStudents are always null. Why? In this howto http://benfoster.io/blog/checkbox-lists-in-aspnet-mvc is written:

The ASP.NET MVC modelbinder is smart enough to map the selected items to this property.

but in my example is always null. Why? How to write more checkboxes and bind it back

You should be using a strongly typed editor to be able to pass the result to the controller (Model binder).

I prefer to do it this way.

Model

public class YourViewModel
{
     public List<SelectListItem> Students
        {
            get;
            set;
        }
}

Controller Get

Students= service.GetStudents(); //Fill the list

View

  @for (var i = 0; i < Model.Students.Count; i++)
                {

                    @Html.CheckBoxFor(m => m.Students[i].Selected)
                    @Html.HiddenFor(m => m.Students[i].Text)
                    @Html.HiddenFor(m => m.Students[i].Value)
                    <span>@Model.Students[i].Text</span>
                }

Controller Post

[HttpPost]
        public ActionResult Create(YourViewModel model)
        {
          foreach(var student in model.Students)
          {
            if(student.Selected) { // Do your logic}
          }
        }

Alternatively You could use an array or List of string. A ListBox is used in this example.

public string[] SelectedStudents{ get; set; }

@Html.ListBoxFor(s => s.SelectedStudents, new MultiSelectList(Model.Students, "Value", "Text", Model.SelectedStudents), new { @class = "form-control", style = "height:250px; width:100%" })

See my answer here How to bind checkbox values to a list of ints? .

The nice thing about this is that it separates concerns between your controller and ui nicely. The html extension methods also create correct html using label and input for the checkbox. and there is no need for hidden fields.

Do you try it with CheckBoxListFor?? You need to associate the checkbox with model and should not have the same ID and name

@Html.CheckBoxListFor(model => model.SelectedSources, Model.SubscriptionSources)

您需要使用可变类型,例如List<string>

public List<string> SelectedStudents { get; set; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM