ViewModels with SelectList Design Decison

一个人想着一个人 提交于 2019-12-03 16:43:16

When dealing with dropdowns in my viewmodels, I usually have a single property associated with the selected list item's value and I have a property that returns a list of selectlistitems. Then, I use Html.DropDownListFor(m => m.ValueProperty, Model.DropDownValues) to render the dropdown.

I imagine in your scenario, you don't have a value corresponding to the selected listitem's value?

Edit: Here's an example from one of my apps...

public class MyVM
{
  public int MyObjectId { get; set; }

  public List<SelectListItem> MyObjectList
  {
    get
    {
      List<SelectListItem> list = (from o in MyObjects select new SelectListItem 
        { Value = o.ObjectId.ToString(), Text = o.ObjectName }).ToList();
      list.Insert(0, new SelectListItem 
        { Value = "0", Text = "[Select an object]" });
      return list;
    }
  }
}

<%: Html.DropDownListFor(m => m.MyObjectId, Model.MyObjectList)%>

You might have noticed the LINQ query that populates the list. In this example, I have a list (MyObjects) that was already populated by AutoMapper. You could simply return a static list if you prefer.

Why not follow the convention which I reckon the majority of people use? You have coupled your ViewModel to your repo which I would also recommend changing. By putting the repo.GetStatuses inside your Controller/Action is simple and it works. I also prefer putting the SelectList inside my view and have the ViewModel house the list of items - but that's my personal preference. You can then clearly see/understand what type of objects your ViewModel deals with. DRY is a principle not a requirement.

ViewModel

public VMPosition
{
    public int StatusId { get; set; }
    public IList<Status> StatusList { get; set; }
}

Controller

public ActionResult UpdatePosition(int id)
{
    var model = new VMPosition(id);
    model.StatusList = _repo.getStatuses;
    return View(model);
}

public ActionResult UpdatePosition(int id, VMPosition Position)
{
    if(!ModelState.IsValid)
    {
        Position.StatusList = _repo.getStatuses;
        return View(Position);
    }
    ...
}

View

<%= Html.DropDownListFor(m => m.StatusId, new SelectList(Model.StatusList)...

Edit - Refactor PopulateSelectLists

public ActionResult UpdatePosition(int id)
{
    var model = new VMPosition(id);
    PopulateSelectLists(model);
    return View(model);
}

public ActionResult UpdatePosition(int id, VMPosition Position)
{
    if(!ModelState.IsValid)
    {
        PopulateSelectLists(Position);
        return View(Position);
    }
    ...
}

private void PopulateSelectLists(VMPosition Position)
{
    Position.StatusList = _repo.GetStatuses;
    Position.OtherSelectList = ...
    ...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!