Alex Rivera | Logout

ASP.NET MVC ViewModel with SelectList(s) best practice

Asked 2011-10-25T17:41:21.473
14

I noticed that in the NerdDinner application that if the ModelState is invalid for a dinner, it merely returns the view for the model:

        if (ModelState.IsValid) {
            ...
            return RedirectToAction("Details", new { id=dinner.DinnerID });
        }

        return View(dinner);

However, in my application the model (a view model in this situation) contains multiple SelectLists. These lists are not instantiated at this point because this view model was just populated from the form submission. What is the recommended way to repopulate this SelectLists before sending them back to the user?

This is what I want my controller to do:

public ActionResult Save(MyModel model)
{
    if (ModelState.IsValid)
    {
        businessClass.Save(model);
        return RedirectToAction("Index", "Home");
    }

    // This won't work because model has uninstantiated SelectLists
    return View("MyView", model);
}

I don't want to send the model to my business logic if the ModelState is invalid, but it doesn't seem to make sense to put SelectList population code in my controller. Should I create a public method in my business logic solely for doing this kind of stuff on my view model(s)?

Edit
Report

1 Answer

1

My controllers populate the SelectLists on my Model if the ModelState is not valid.

Following Separation of Concerns, your business classes shouldn't know anything about the view model at all. If your view needs a list of employees your controller gets a list of employees from your business layer and creates the SelectList that your view needs.

Example

public ActionResult Save(MyModel model) 
{ 
    if (ModelState.IsValid) 
    { 
        businessClass.Save(model); 
        return RedirectToAction("Index", "Home"); 
    } 
    model.PossibleEmployees 
             = _employeeRepository.All().Select(e => 
                                                new SelectListItem{Text=e.Name, 
                                                                   Value=e.Id});
    return View("MyView", model); 
} 

Update

If your select list population code is determining WHICH options to present I think you probably should move that to a service in your business layer. If reusability is the big concern, rouen's answer looks like it has the most possibility for reuse.

answered 2011-10-25T18:30:00.277

Your Answer