简体   繁体   中英

Binding posted values to view model using default binder - MVC3

Can the Model Binder in MVC bind posted values to a view-model object containing hierarchy?

I have a Customer, Order and OrderItem tables. OrderItem.OrderID points to Order.ID; and Order.CustomerID points to Customer.ID ie the common Customer -> Order -> OrderItem setup.

And I have a view model – Customer which contains Order objects and then OrderItem objects as well.

I have created the EF model objects using the designer tools in VS. (created database tables first in SQL, then created the classes automatically using the EF tools)

On a single page (view), let's say, I will allow the user to create a new Customer record, an Order, and some OrderItem(s).

When the user fills the form (creates a new Customer, Order and OrderItems on this one view), clicks on the submit button; will the default binder move all the values from the posted values to my view model? (the view model class carries properties for Customer, Order, OrderItem in a hierarchy ie Order is a property within Customer and OrderItem is a property within Order). Is EF smart enough to map posted values to such an object?

Yes, MVC is smart enough to handle this binding. It is fairly common in MVC to build up a 'complex' View Model made of several properties which are themselves Models. Binding to collections and dictionaries is harder, but entirely possible.

In EF, you can easily define relationships between objects (eg there is a 1 to many relationship between Customer and Order), and EF will handle this just fine. The code for the 'Create customer with order and order items' will (I imagine) be fairly straightforward but I'm not an EF expert, though - so I will have to leave detailed answers to someone else.

However, the EF code for an 'Edit Customer and/or Order and/or Items' screen would actually be quite complicated - and so you'd probably be better splitting these off into separate actions, as this would simplify the code quite a lot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM