【问题标题】:DropDownListFor not directly connected to modelDropDownListFor 未直接连接到模型
【发布时间】:2015-03-13 08:04:07
【问题描述】:

在我想用于登录的表单中使用 DropDownListFor 助手时遇到了困难(安全性不是这里的问题)。 我不想让用户输入其用户名,而是让他从下拉列表中选择它。

但我无法让 ASP.NET 自动将我的模型的 EmpName 属性设置为下拉列表中的选定值。

这是我尝试过的:

以下方法显示登录页面

[HttpGet]
public ActionResult Index()
{
   // Retrieving all users from DB
   using (var db = new BidManagementContext())
   {
       var users = from u in db.LOGIN
                   select u.EmpName;

       ViewBag.AllUsers = new SelectList(users.ToList());
       return View();
   }
}

这些是视图中的一些线:

<div class="form-group">
   @Html.LabelFor(model => model.EmpName, htmlAttributes: new { @class = "control-label col-md-2" })
   <div class="col-md-10">
       @Html.DropDownListFor(model => model.EmpName, ViewBag.AllUsers as SelectList, new { @class = "form-control" })
   </div>
</div>

按照我的做法,当 ASP.NET 尝试将下拉选择的值绑定到模型时出现错误:

System.Web.Mvc.dll 中出现“System.InvalidOperationException”类型的异常,但未在用户代码中处理

附加信息:没有具有键“EmpName”的“IEnumerable”类型的 ViewData 项。

我不确定在这里做什么:-/

【问题讨论】:

  • 表示ViewBag.AllUsers 为空。可能您在提交后返回视图但未重新分配 SelectList
  • 您是否为视图定义了模型类型?
  • @StephenMuecke 哦,就这么简单......我觉得有点愚蠢:-/你会在评论之外回复帖子,以便我可以投票并将你的答案标记为解决方案吗?
  • 我认为你应该为下拉列表中的元素建立一个数据类型(类),并且该类必须有一个名为 EmpName 的字段。

标签: c# asp.net-mvc


【解决方案1】:

错误信息表示ViewBag.AllUsers 的值为空。这可能是因为您在提交后返回视图但没有重新分配SelectList。我建议将用于填充 SelectLists 的代码重构为一个私有方法,如果您返回视图,该方法可以在 GET 和 POST 方法中调用。

编辑(添加示例)

HttpGet]
public ActionResult Index()
{
  YourViewModel model = new YourViewModel();
  ConfigureViewModel(model);
  return View(model);
}

[HtppPost]
public ActionResult Index(YourViewModel model)
{
  if (!ModelState.IsValid)
  {
    ConfigureViewModel(model);
    return View(model);
  }
  // Save and redirect
}

private void ConfigureViewModel(YourViewModel model)
{
  using (var db = new BidManagementContext())
  {
    var users = from u in db.LOGIN select u.EmpName;
    ViewBag.AllUsers = new SelectList(users.ToList());
    // or better, model.AllUsers = new SelectList(users.ToList());
  }
  // any other common operations
}

【讨论】:

    猜你喜欢
    • 2019-02-19
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-02
    • 2018-07-10
    • 1970-01-01
    相关资源
    最近更新 更多