ASP.NET MVC - View Model Models

I have been working with the MVC framework (ASP.NET MVC2 / 3 / Razor) for several months now, and I really like it, but it's hard for me to define a standard for view models. In my projects, I have a Models folder (contains my data models - Linq DBML, Repository [ies], extension methods) and a Models / ViewModels folder. My view model is usually reusable classes that usually contain simple get / set properties for LINQ objects or collections of objects that I need to access a specific view.

Now the problem I am facing is figuring out when to create a view model. My goal is to use the LINQ object as a representation model as often as possible, especially when this is the "Edit" action. My problem is that if I have other bits of data that I can only use for display? I do not like to use ViewData / ViewBag collections, since accessing members from them requires knowing the key of the collection element (it is not easy for the designer / front guy to “guess”). I also don't like the idea of ​​creating a ViewModel for each view, as this seems like overly dirty code.

For example, imagine that I have a data model for Employee, and I want to display some information that is not related to this employee — say, site statistics, dynamic menus, and all you can think of is that it could come from a database . Which model should be passed to the action / Employee / Change? An Employee object with a bunch of ViewData [] for the rest, or a custom EmployeeView?

Is there a gold standard? What am I missing? What do you do differently, what should I look at? Thanks in advance!

+3
source share
3 answers

You have named three things here:

  • Site statistics
  • Dynamic menus
  • Whatever you [...] come from the database

- ; , - , , .

. . , . , (, ), .

, , , ( Google). -, , .

, , . /, , . - . ViewData/ViewBag , , .

, , , : , - , "MVC", " ". , , - - .

MVC, . , , , , "" . - ; , . .

, , , . , , , , - . tv, AutoMapper, 30 .

, .

+2

. , . AutoMapper . ModelMapper, ToViewModel<TEntity,TViewModel>() ( automapper) , .

+3

If you create a page for editing an employee, but also display what you mentioned (site / menu statistics), why not put them in partial views or layout files?

0
source

All Articles