Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 699
mbrc Avatar asked Dec 10 '22 19:12

mbrc


2 Answers

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%" })
like image 148
Moe Avatar answered Dec 13 '22 07:12

Moe


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.

like image 27
Fran Avatar answered Dec 13 '22 08:12

Fran