开发者

ASP.NET MVC 2: Any way to pass two Objects to a Template?

开发者 https://www.devze.com 2023-01-13 11:09 出处:网络
A \"Lookup\" in this example is an IList<string> of state abbreviations.Generally, your Domain Model POCOs won\'t include these options.ViewModels usually take this responsibility referencing bo

A "Lookup" in this example is an IList<string> of state abbreviations. Generally, your Domain Model POCOs won't include these options. ViewModels usually take this responsibility referencing both the original Domain Model as well as the Lookup object, but 开发者_JAVA技巧what happens when the Domain Models are nested and you are using MVC templates (which won't have access to the original Model's root properties?

Is there a way to include the Lookups in one object and the Model in a different object for the template? Is it permissible to assemble on-the-fly a ViewModel specific to that Template within the View (which would have to include any nested data from there)? I would think static methods to pull down Lookup values is bad.

Any ideas?

Notes (to my knowledge):

A Domain Model POCO from a repository doesn't change in structure. If you need a single Model to have both the Customer object and the DDL options for US State for example, you normally have a ViewModel that references the Customer object and the Customer Lookup lists.

However, when you have a nested Domain Model (aggregate root), the nested objects have no where to put the Lookup Lists, and the MVC templates cannot access the root level View Model (their view model is the partial Model).

Edit:

Is there some way to put the DDL lists in the root level of the ViewModel, then when you get to the Customer object, construct a new ViewModel that references the root level DDL lists and the current Customer object to send to the template? This would eliminate duplicate data in the Model as well as use a single Model for all the Views. The only bad would be Controller like data assembly code in your view (which is just as bad).


A couple of suggestions. First, use separate view models for your views -- don't directly use your domain models. These view models can, and should, carry the extra data needed by the view. Second, you can use the overloads on DisplayFor/EditorFor to pass additional view data to the template. That way your template can be specific to a particular domain model and yet have access to the additional data in the view model.


For static, unchanging lists like state abbreviations, you could use Application state or Cache entry. These types of lists could be loaded in Application_Start from a database.

0

精彩评论

暂无评论...
验证码 换一张
取 消