asp.net mvc - MVC Passing ViewModel to @Html.Partial -
passing viewmodel @html.partial
have 2 viewmodels
public class registervm { ... properties public addressvm addressinformation { get; set; } //viewmodel } public class addressvm { public string street1 { get; set; } public string street2 { get; set; } public string postalcode { get; set; } }
when loading main view using vm:
@model viewmodels.registervm
all field load. when add partial view , pass viewmodel
@html.partial("_addressdetails", model.addressinformation)
it fails error: exception details: system.nullreferenceexception: object reference not set instance of object. why fail?
the partial view _addressdetails expecting
@model viewmodels.addressvm
update
based on changes prashant,
when submitting information address information null. in controller:
[httppost] public actionresult register(registervm vm){ ... //when viewing vm.addressinformation.street1 null. , there value //is there different way of retrieving values partial view? }
thanks reading.
the error generated because property addressinformation
null, , need initailize in parameterless constructor or in controller before pass view, example
public class registervm { public registervm() // default constructor { addressinformation = new addressvm(); } public addressvm addressinformation { get; set; } .... }
however usage means controls generated be
<input name="street1" .../>
whereas need
<input name="addressinformation.street1" .../>
in order bind model. can either make partial editortemplate
(/views/shared/editortemplates/addressvm.cshtml
) , use in main view as
@html.editorfor(m => m.addressinformation)
or pass prefix partial additional viewdata
@html.partial("_addressdetails", model.addressinformation, new viewdatadictionary { templateinfo = new templateinfo { htmlfieldprefix = "addressinformation" }})
Comments
Post a Comment