asp.net - Model Binding binding at more than one level -
i have several forms, require checkbox each province/state. therefore, i've made partial view render checkboxes inside form promote code re-use. when user submits form controller method, regionsviewmodel not binded. overall question is, how can multiple forms share partial view , view model?
here's sample code of situation models
public class form1viewmodel { /* properties */ public regionsviewmodel regions {set; get;} } public class form2viewmodel { /* properties */ public regionsviewmodel regions {set; get;} } public class form3viewmodel { /* properties */ public regionsviewmodel regions {set; get;} } public class regionsviewmodel { public bool on {set; get;} public bool qc {set; get;} /* continues provinces , states */ }
controller
[httppost] public actionresult form(form1vewmodel model) { //all properties except model.regionviewmodel not bind submitted form :( }
form1viewmodel.aspx
<% using (html.beginform()) {%> <!-- binds 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 provinces , states -->
update replaced "model.regionselectorvm" "model.region". finding bug in demo code darin dimitrov.
what regionselectorvm
? seems type of partial. try editor templates. it's cleaner:
<% using (html.beginform()) { %> <!-- binds property --> <%= html.editorfor(x => x.regions) %> <input type="submit" value="submit form!" /> <% } %>
and inside ~/views/shared/editortemplates/regionsviewmodel.ascx
:
<%@ control language="c#" inherits="system.web.mvc.viewusercontrol<appname.models.regionsviewmodel>" %> <%= html.checkboxfor(x => x.on) %> on <%= html.checkboxfor(x => x.qc) %> qc <!-- continue inputs provinces , states part of regionsviewmodel model -->
now should bind correctly.
Comments
Post a Comment