As you understand, there are many ways to achieve your goal. While the MVC design template encourages certain application organizations, how you organize your models, views, and controllers is ultimately a matter of preference.
Scott Allen discusses his preference for dealing with ASP.NET MVC drop-downs in a blog post. Scott uses an extension method to convert an enumerated complex type to IEnumerable<SelectListItem> in his model. He then describes that after submitting, ASP.NET MVC will not return the IEnumerable<SelectListItem> that it sent to the view, but only the value that the user selected. He then suggests that using two models can simplify the situation.
This is a reasonable description of what I call ViewModels and FormModels. The ViewModel transfers the displayed data to the view, and the FormModel is used to transfer the collected data back to the controller action. Further clarify:
- ViewModels contain data that helps visualize views. By organizing my ViewModels in this way, I can put all the necessary information to display a specific view in a related model. This stops me from using ViewData for anything that is not really temporary.
- FormModels are used to collect user data. FormModels (almost) never contain references to other complex types and consist of primitives, DateTimes, and strings.
In any case, I have a strict rule: never use the model for another view . Having your models closely associated with the views used to render them makes it easy to record your views. You donβt need to worry about things like static methods because your models need to transfer data to their associated representations in a form that is easy to visualize. Tools such as AutoMapper can help smooth out domain objects in models for display.
For additional verification: ASP.NET MVC terminology disables me - why "ViewModel"?
ahsteele
source share