11

After reading this question ASP.NET MVC: Nesting ViewModels within each other, antipattern or no?

and Derick Bailey's comment

i think the "consider what your viewmodel would look like as xml or json" bit is probably the most important point, here. i often use that perspective to help me understand what the view model should look like, and to help me understand what data is "viewmodel" data vs "data that goes on the HTML rendering of the view". helps to keep things clean and separate them nicely – Derick Bailey Apr 11 '11 at 15:45

It makes me wonder how I would approach creating a View for a ViewModel with databound selection items. I'm really struggling because I can't envision where the SelectList belongs. If I think in terms of JSON or XML then the SelectList is part of the View Only. All I want is a dropdown list prepopulated with a list of values for the user to select the Location Having it in the ViewModel seems wrong, but when I think about moving it to the View I don't know where to place the logic to pull from the DB to populate the Selection List

public class SearchViewModel
{
    public int? page { get; set; }
    public int? size { get; set; }
    //Land Related search criteria        
    [IgnoreDataMember]
    public SelectList LocationSelection{ get; set; }

update

Here is a great question and answer that is really closely related C# mvc 3 using selectlist with selected value in view

I've tested this implementation and it does what I think I want to do. I'm not going to rush to pick an answer as I still haven't fully vetted this out.

Community
  • 1
  • 1
Doug Chamberlain
  • 11,192
  • 9
  • 51
  • 91

2 Answers2

1

I'd refactor your viewModel along the following lines as I don't believe that selectlists should belong in the viewmodel:

public class SearchViewModel
{
    public int? page { get; set; }
    public int? size { get; set; }
    //Land Related search criteria        
    public IEnumerable<Location> LocationSelection{ get; set; }
}

and in your view, populate the viewModel as such:

public ActionResult Search()
{
    var viewModel = new SearchViewModel()
    {
        viewModel.LocationSelection = _repository.All<Location>()
    };

    // any other logic here or in service class
    return View(viewModel);
}

then in your view, you'd use the html.dropdownlist helper to display your items. works for me

jim tollan
  • 22,305
  • 4
  • 49
  • 63
0

I try to avoid SelectLists, as they do not seem to fit well into the MVC model. Instead I create helpers to generate my HTML elements from IEnumerable types in the model. I think this maintains the general rule of keeping the pure data in the model, and the display logic in the view.

But that's just my personal take. I think creating SelectLists for the express purpose of displaying data in the view is silly.

Jeremy Holovacs
  • 22,480
  • 33
  • 117
  • 254