public class checkbox
{
int id;
string name;
bool selected;
}
and I call this in viewmodel as List<checkbox> list
when I am binding the list into view is successfully but when I am getting the selected values the model data shows list: count=0 when selected otherwise shows null
@foreact(var item in model.list){
<input type="checkbox" @selected name="list" value="@item.id">
}
how can I get these values from view to controller
this is not good
Siva_540
name="list"
Please read http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/
Hi Siva,
assign a name to your checkbox:
<input name="gender" type="checkbox" id="@checkBoxId" class="chkclass" value="@names.Value" />
Then in your action do something like below:
[HttpPost] public ActionResult HandleFormSubmit(string[] gender, MembershipFormViewModel model) { //model not valid, do not save, but return current umbraco page if (ModelState.IsValid == false) { return CurrentUmbracoPage(); } string test = "Gender: " + model.Gender + Environment.NewLine; //getting null here return RedirectToCurrentUmbracoPage(); }
you need to understand how checkboxes post their data. if they have a name attribute, when checked, they post name=value, else if not checked its value is not included in the postback data. so if you had three checkboxes
<input type="checkbox" name="list" value="1" checked>
<input type="checkbox" name="list" value="2" >
<input type="checkbox" name="list" value="3" checked>
and the user did not change the check, the postback data would include:
list=1&list=2
the mvc binder can bind this data to a string array or numeric array. but that is not what you have. if you change the checkboxes to:
<input type="checkbox" name="list.id" value="1" checked>
<input type="checkbox" name="list.id" value="2" >
<input type="checkbox" name="list.id" value="3" checked>
the binder could blind it your list, but it would only contain 2 entries, and only the id would be filled in. to get you complete list posted back it would be:
@for(var i=0; i < model.list.Count; ++i){ @Html.HiddenFor(m=>m.list[i].id) @Html.HiddenFor(m=>m.list[i].name) @Html.CheckboxFor(m=>m.list[i].selected) }
if you wanted to manually handle the checkbox its:
<input type="checkbox" @(Model.list[i].selected ? "checked" : "") name="list[@(i)]" value="true">