I have a view with a table that displays my model items. I\'ve extracted the relevant portions of my view:
@model System.Collections.Generic.IEnumerable
You cannot use a foreach
loop to generate form controls for properties in a collection. It creates duplicate name
attributes (in your case name="item.IncludeProvision"
) which have no relationship to your model and duplicate id
attributes which is invalid html. Use either a for
loop (you models needs to be IList<Provision>
for(int i = 0; i < Model.Count; i++)
{
<tr>
<td>....</td>
<td>@Html.CheckBoxFor(m => m[i].IncludeProvision)<td>
</tr>
}
or create an EditorTemplate
for typeof Provision
. In /Views/Shared/EditorTemplates/Provision.cshtml
(note the name of the template must match the name of the type)
@model Provision
<tr>
<td>....</td>
<td>@Html.CheckBoxFor(m => m.IncludeProvision)<td>
</tr>
and in the main view (the model can be IEnumerable<Provision>
)
<table>
@Html.EditorFor(m => m)
</table>
As @mattytommo said in comments, you should post your model to controller. It can be done with putting your checkbox inside a form. After clicking on button "Save and exit" all data from inputs inside this form will be serialized and sent to your controller where you can perform manipulations with session variables and so on. After that you can redirect wherever you like.
Model
public class YourModel
{
...
public bool IncludeProvision { get; set; }
...
}
View
@model YourModel
...
@using (Html.BeginForm("SaveAndSend", "Test", FormMethod.Post))
{
...
@Html.CheckBoxFor(model => model.IncludeProvision)
...
<button type="submit">Save and send</button>
}
...
Controller
public class TestController : Controller
{
...
[HttpPost]
public ActionResult SaveAndSend(YourModel model)
{
if (ModelState.IsValid)
{
// Some magic with your data
return RedirectToAction(...);
}
return View(model); // As an example
}
...
}