I have several forms, all which require a checkbox for each province/state. Therefore, I’ve made a partial view to render the checkboxes inside a form to promote code re-use. But when the user submits the form to a controller method, the RegionsViewModel does not get binded. The overall question is, how can I get multiple forms to share a partial view and view model?
Here’s a sample code of my situation
Models
public class Form1ViewModel
{
/* Some properties */
public RegionsViewModel Regions {set; get;}
}
public class Form2ViewModel
{
/* Some properties */
public RegionsViewModel Regions {set; get;}
}
public class Form3ViewModel
{
/* Some properties */
public RegionsViewModel Regions {set; get;}
}
public class RegionsViewModel
{
public bool ON {set; get;}
public bool QC {set; get;}
/* this continues for all provinces and states */
}
Controller
[HttpPost]
public ActionResult Form(Form1VewModel model) {
//All properties except for model.RegionViewModel does not bind properly to the submitted form :(
}
Form1ViewModel.aspx
<% using (Html.BeginForm())
{%>
<!-- Binds some property -->
<% Html.RenderPartial("Controls/RegionSelector", Model.Regions); %>
<input type="submit" value="Submit Form!" />
<%}%>
Controls/RegionSelector.ascx
<%=Html.CheckBoxFor(x => x.AvailableProvince_ON> ON
<%=Html.CheckBoxFor(x => x.AvailableProvince_QC> QC
<!-- Binds to all provinces and states -->
Update
Replaced “Model.RegionSelectorVm” with “Model.Region”. Thanks for finding the bug in my demo code Darin Dimitrov.
What is
RegionSelectorVm? It seems that this is the type of your partial. Try with editor templates. It’s cleaner:and inside
~/Views/Shared/EditorTemplates/RegionsViewModel.ascx:Now everything should bind correctly.