Note that there are some explanatory texts on larger screens.

plurals
  1. POFetching data within an ASP.NET MVC ViewModel class?
    primarykey
    data
    text
    <p>For those that create ViewModels (for use by typed views) in ASP.NET MVC, do you prefer to fetch the data from a service/repository from within the ViewModel, or the controller classes?</p> <p>For example, we started by having ViewModels essentially being DTOs and allowing our Controllers to fetch the data (grossly oversimplified example assumes that the user can only change employee name):</p> <pre><code>public class EmployeeViewModel { public String Name; //posted back public int Num; //posted back public IEnumerable&lt;Dependent&gt; Dependents; //static public IEnumerable&lt;Spouse&gt; Spouses; //static } public class EmployeeController() { ... public ActionResult Employee(int empNum) { Models.EmployeeViewModel model = new Models.EmployeeViewModel(); model.Name = _empSvc.FetchEmployee(empNum).Name; model.Num = empNum; model.Dependents = _peopleSvc.FetchDependentsForView(empNum); model.Spouses = _peopleSvc.FetchDependentsForView(empNum); return View(model); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Employee(Models.EmployeeViewModel model) { if (!_empSvc.ValidateAndSaveName(model.Num, model.Name)) { model.Dependents = _peopleSvc.FetchDependentsForView(model.Num); model.Spouses = _peopleSvc.FetchDependentsForView(model.Num); return View(model); } this.RedirectToAction(c =&gt; c.Index()); } } </code></pre> <p>This all seemed fine until we started creating large views (40+ fields) with many drop downs and such. Since the screens would have a GET and POST action (with POST returning a view if there was a validation error), we'd be duplicating code and making ViewModels larger than they probably should be. </p> <p>I'm thinking the alternative would be to Fetch the data via the Service within the ViewModel. My concern is that we'd then have some data populated from the ViewModel and some from the Controller (e.g. in the example above, Name would be populated from the Controller since it is a posted value, while Dependents and Spouses would be populated via some type of GetStaticData() function in the ViewModel).</p> <p>Thoughts?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload