KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
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? 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): public class EmployeeViewModel { public String Name; //posted back public int Num; //posted back public IEnumerable<Dependent> Dependents; //static public IEnumerable<Spouse> 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 => c.Index()); } } 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. 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
Tags (comma-separated)
Save Edits
Cancel