【问题标题】:Assign viewbag int value to Html Helper Dropdown list将 viewbag int 值分配给 Html Helper 下拉列表
【发布时间】:2019-08-30 06:45:38
【问题描述】:

我正在尝试将 view-bag 中存在的 int 值分配给下拉列表。

查看

@Html.DropDownListFor(m => m.nStatusID, ViewBag.ReasonTypeList asSelectList,ViewBag.nStatusID, new { @class = "form-control" })

控制器动作包含-

var Complaint = db.ComplaintRegistrations.SingleOrDefault(x => x.nCallID == id);
ViewBag.nStatusID = Complaint.nStatusID;
List<ReasonTypeMaster> ReasonTypeList = db.ReasonType.ToList();
ViewBag.ReasonTypeList = new SelectList(ReasonTypeList, "nReasonTypeID", "cReasonType");

错误- “System.Web.Mvc.HtmlHelper”没有名为“DropDownListFor”的适用方法,但似乎具有该名称的扩展方法。扩展方法不能动态调度。考虑强制转换动态参数或调用扩展方法而不使用扩展方法语法。

【问题讨论】:

    标签: c# model-view-controller asp.net-mvc-5 html-helper


    【解决方案1】:

    看起来您想要设置下拉列表的选定值,您需要在模型对象中设置它,并且助手将负责设置为选定的。试试看:

    var Complaint = db.ComplaintRegistrations.SingleOrDefault(x => x.nCallID == id);
    if(Complaint != null)
        model.nStatusID = Complaint.nStatusID;
    
    List<ReasonTypeMaster> ReasonTypeList = db.ReasonType.ToList();
    ViewBag.ReasonTypeList = new SelectList(ReasonTypeList, "nReasonTypeID", "cReasonType");
    
    return View(model);
    

    在 View 中您只需要:

    @Html.DropDownListFor(m => m.nStatusID, 
                          ViewBag.ReasonTypeList asSelectList, 
                          new { @class = "form-control" })
    

    m.nStatusID 将具有您在控制器操作中设置的值,并将填充为在下拉元素中选择。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-10
      • 2013-07-08
      相关资源
      最近更新 更多