加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 带SelectList Design Decison的ViewModels

发布时间:2020-12-16 07:31:27 所属栏目:asp.Net 来源:网络整理
导读:我创建了一个viewmodel public VMPosition{ public VMPosition(){}//for model binder public VMPosition(int EmployeeID) { PositionStatusList = new SelectList(_repo.getStatuses); //populate other properties } public int CurrentPositionID { get;
我创建了一个viewmodel

public VMPosition
{
        public VMPosition(){}//for model binder  
        public VMPosition(int EmployeeID)
        {
            PositionStatusList = new SelectList(_repo.getStatuses);
            //populate other properties
        }
        public int CurrentPositionID { get; set; }
        public int EmployeeID { get; set; }
        public int CurrentPositionHistoryID { get; set; }
        public bool AddingNew { get; set; }
        public bool ClosingCurrent { get; set; }
        public string CurrentPosition { get; set; }
        public DateTime CurrentPositionStartDate { get; set; }
        public string ReasonForDeparture { get; set; }
        public SelectList PositionStatusList { get; set; }

}

我的GET ActionResult被定义为

public ActionResult UpdatePosition(int id)
{
     return View(new VMPosition(id)); 
}

我的POST动作结果定义为

public ActionResult UpdatePosition(int id,VMPosition Position)
    {
        if(ModelState.IsValid){
             Position Current = new Position{Position.Title etc..}
             //save to db
             return redirectToAction("someAction");
         }
         return View(Position);//here is the problem
    }

我的SelectList填充在一个接受一个参数的构造函数中.如果modelstate无效,Modelbinder不能也不应该调用构造函数.我将不得不返回带有模型对象的View(在这种情况下不包含SelectList值).使用视图模型时如何处理这种情况.

我可以在actionresult中手动填充这些值,但这会违反DRY原则.但是,出于这个问题的目的,我想帮助解决更大的设计问题.

解决方法

在我的视图模型中处理下拉列表时,我通常会有一个与所选列表项的值相关联的属性,并且我有一个返回selectlistitems列表的属性.然后,我使用Html.DropDownListFor(m => m.ValueProperty,Model.DropDownValues)来呈现下拉列表.

我想在你的场景中,你没有与所选列表项的值相对应的值?

编辑:这是我的一个应用程序的示例…

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)%>

您可能已经注意到填充列表的LINQ查询.在这个例子中,我有一个已经由AutoMapper填充的列表(MyObjects).如果您愿意,您可以简单地返回一个静态列表.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读