Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# DropDownListFor未直接连接到模型_C#_Asp.net Mvc - Fatal编程技术网

C# DropDownListFor未直接连接到模型

C# DropDownListFor未直接连接到模型,c#,asp.net-mvc,C#,Asp.net Mvc,我在使用DropDownListFor帮助程序进行登录时遇到了困难(这里不涉及安全性)。 我想让用户从下拉列表中选择用户名,而不是要求用户键入用户名 但我无法使ASP.NET自动将模型的EmpName属性设置为下拉列表中的选定值 这是我尝试过的: 以下方法显示登录页面 [HttpGet] public ActionResult Index() { // Retrieving all users from DB using (var db = new BidManagementCont

我在使用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>

@LabelFor(model=>model.EmpName,htmlAttributes:new{@class=“controllabel col-md-2”})
@Html.DropDownListFor(model=>model.EmpName,ViewBag.AllUsers作为SelectList,新建{@class=“form control”})
关于我的操作方式,当ASP.NET尝试将下拉选择值绑定到模型时,我出现了一个错误:

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

其他信息:“IEnumerable”类型的ViewData项没有键“EmpName”


我不知道该怎么办:-/

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

编辑(添加示例)


这意味着
ViewBag.alluser
为空。可能您在提交后返回视图,但没有重新分配
SelectList
您是否为视图定义了模型类型?@StephenMuecke噢,就是这么简单。。。我觉得有点愚蠢:-/你能在评论之外回答帖子吗,这样我就可以投票并将你的答案标记为解决方案?我认为你应该为下拉列表中的元素构建一个数据类型(类),并且该类必须有一个名为EmpName的字段。
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
}