Get Help:Ask a Question in our Forums|Report a Bug|More Help Resources
Last post Apr 19, 2012 08:02 PM by garfbradaz
Apr 18, 2012 07:57 PM|LINK
I have a question on stackoverflow here which im stuck on concerning ViewModels and binding the POST:
If using ViewModel, I was was always under the Impression that the View declared the ViewModel (passed by the GET ActionMethod) but when posting back, the POST ActionMethod declares the Model only and the Model Binder will handle the rest
Am i completely wrong on this?
Apr 18, 2012 08:23 PM|LINK
I looked at your code and your POST action method needs to receiev an instance of your LedgerUserViewModel and not LedgerUser. The reason for this is because in your view the action helpers are configured to generate markup for LedgerUserViewModel.
@Html.EditorFor(model => model.LedgerUser.AccountNumber)
Creates the html so that the name of the html element (which the model binder uses) will map to a property called AccountNumber on the LedgerUser object and not the model itself. Meaning that the model binder is expecting an objec that has a LedgerUser property,
not a ledger user itself.
Now your can have a view model and model work togther with the model binder taking care of the difference, but in those cases you need to hae similar properties on both objects. The model binder works strictly off property names. In those cases the view
model would have properties corresponding to the individual model properites, instead of a single property for the model.
Apr 19, 2012 01:09 AM|LINK
See my answer in your stackoverflow question:
Apr 19, 2012 08:02 PM|LINK
Thanks fot your time. The error was caused because i was returning LedgerUser instead of LedgerUserViewModel. Ive fixed that and it works now. Now i also changed the following
public ActionResult Create(bool Thumbnail,LedgerUser ledgerUser, HttpPostedFileBase imageLoad2)
public ActionResult Create(bool Thumbnail,LedgerUser LedgerUser, HttpPostedFileBase imageLoad2)
This allowed me to reference the LedgerUser model. If i used LedgerUserViewModel there properites in LedgerUserViewModel LedgerUser property were null.
My full working code can be found here: