I have a view model for a business. This model conatains a view model for address, contact details and also an IEnumerable.
I use editor templates to display the checkboxes. The problem is when I'm on the edit action and post the form the categories come back as null. I have read a few similar questions but havent found a solution that seems to work.
I have looked into Custom model binders with no luck and currently I'm thinking I'm not displaying the right information in the Editor template. I know checkboxes need a hidden input to go with them and maybe my problem lays there?
BusinessViewModel
public class BusinessViewModel
{
public int? Id { get; set; }
[UIHint("ContactDetailsEditorTemplate")]
public ContactDetailsViewModel ContactDetailsViewModel { get; set; }
[UIHint("CheckboxEditorTemplate")]
public IEnumerable<CheckboxViewModel> Categories { get; set; }
}
CheckboxViewModel
public class CheckboxViewModel
{
public int CategoryId { get; set;}
public string Description { get; set;}
public bool Checked { get; set; }
}
CheckboxEditorTemplate
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<ViewModels.BuyWithConfidence.CheckboxViewModel>>" %>
<table class="aligncenter">
<tr class="tRow left"><%
var intBreakLine = 0;
if (Model != null)
{
foreach (var category in Model)
{
if (intBreakLine >= 2)
{
intBreakLine = 0;%>
</tr>
<tr class="tRow left"><%
}%>
<td>
<%= Html.Hidden(string.Format("Categories[{0}].CategoryID", i), category.CategoryId) %>
<%= Html.CheckBox(string.Format("Categories[{0}].Checked", i), category.Checked) %>
</td>
<td><%=category.Description%></td><%
intBreakLine = intBreakLine + 1;
i = i + 1;
}
}%>
</tr>
</table>
This is a snippet of what the template is producing:
<input id="Categories_Categories_0__CategoryID" name="Categories.Categories[0].CategoryID" type="hidden" value="1" />
<input id="Categories_Categories_0__Checked" name="Categories.Categories[0].Checked" type="checkbox" value="true" /><input name="Categories.Categories[0].Checked" type="hidden" value="false" />