Reputation: 2938
I have a Form
which is filled with some grid like structure with CheckBoxes
and DisplayField
.
I want to fetch rows with Checked CheckBoxes
. Problem is i am getting null in Controller's post
method.
Models
public class RegisterModuleSelection
{
[Display(Name = "ID")]
public int mID { get; set; }
[Display(Name = "Module")]
public string Module { get; set; }
[Display(Name = "Buy")]
public bool Buy { get; set; }
}
View
@model IEnumerable<MAK_ERP.Models.RegisterModuleSelection>
@{
ViewBag.Title = "Register - Modules Selection";}
<h2>
Register - Modules Selection</h2>
@using (Html.BeginForm("RegisterModules", "UserAccount", FormMethod.Post, new { id = "RegisterModules", @class = "generalForm" }))
{
<table class="Grid Module">
<tr>
<th>
@Html.DisplayNameFor(model => model.Module)
</th>
<th>
@Html.DisplayNameFor(model => model.Price)
</th>
<th>
@Html.DisplayNameFor(model => model.Duration) (Months)
</th>
<th>
@Html.DisplayNameFor(model => model.Buy)
</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.HiddenFor(modelItem => item.mID)
@Html.DisplayFor(modelItem => item.Module)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.EditorFor(modelItem => item.Duration)
</td>
<td>
@Html.CheckBoxFor(modelItem => item.Buy)
</td>
</tr>
}
<tr>
<td colspan="4">
<input type="submit" value="Next" class="button3" />
<input type="reset" value="Reset" class="button4" />
</td>
</tr>
</table>
}
Controller
[HttpGet]
public ActionResult RegisterModules()
{
IEnumerable<MAK_ERP.Models.RegisterModuleSelection> model = reg.getModules();
return View(model);
}
[HttpPost]
public ActionResult RegisterModules(IEnumerable<Models.RegisterModuleSelection> regMod)
{
//regMod is null here
...
Upvotes: 0
Views: 1618
Reputation: 3204
You should use EditorTemplates
to solve the problem.
The accepted answer at ASP.NET MVC Multiple Checkboxes would help you.
Upvotes: 0
Reputation: 7943
Unfortunately you cannot bind in this way. Model binding depends upon how generated html looks like.
In this particular case it should look something like:
<input id="item_Buy" type="checkbox" value="true" name="item[0].Buy" checked="checked">
If you are okay with some workarounds, you can use a for loop instead of foreach loop where you can add an index to each control name and model binder could bind them properly.
There are some really helpful discussions available, you can check here: ASP.NET MVC - Insert or Update view with IEnumerable model. And also Model Binding To A List. Another one is: Modelbinding IEnumerable in ASP.NET MVC POST?
Upvotes: 2