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; }
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With