在ASP.NET MVC数据库中插入下拉列表值

时间:2019-06-24 14:58:44

标签: asp.net-mvc

我要从控制器插入数据库中的下拉列表值:

 public ActionResult PostMessage(ViewModel vm)
    {
        Models.Message messagetoPost = new Models.Message();
        ViewBag.Userlist = new SelectList(dbContext.Users, "Id", "UserName");
        ViewBag.Userlist = messagetoPost.MessageTosend;

        dbContext.Messages.Add(messagetoPost);
        dbContext.SaveChanges();
    }

查看

  @Html.DropDownList("Userlist", null, htmlAttributes: new { @class = "form-control" })

2 个答案:

答案 0 :(得分:0)

您使用了错误的签名。您需要在ViewModel中选择选定的值,例如UserId

@Html.DropDownList("UserId", ViewBag.Userlist, null, htmlAttributes: new { @class = "form-control" })

或更好

@Html.DropDownListFor(m => m.UserId, ViewBag.Userlist, "Select User", htmlAttributes: new { @class = "form-control" })

最后,您还有其他错误(假设这是您要保存的POST方法)。将发布的viewmodel字段复制到您的Message实体中并保存(如果没有错误):

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult PostMessage(ViewModel vm)
{
    if (ModelState.IsValid)
    {
        Models.Message messagetoPost = new Models.Message
        {
              UserId = vm.UserId;
              ... other fields
        };
        dbContext.Messages.Add(messagetoPost);
        dbContext.SaveChanges();
        return RedirectToAction("Index");
    }
    // Failed, reset dropdown and return view with errors...
    ViewBag.Userlist = new SelectList(dbContext.Users, "Id", "UserName");
    return View(complianceItemViewModel);
}

答案 1 :(得分:0)

@Html.DropDownList("Userlist", null, htmlAttributes: new { @class = "form-control" })

更改

 @Html.DropDownList("User",ViewBag.Userlist, null, htmlAttributes: new { @class = "form-control" })

在此位置,“用户” 是下拉列表名称的名称

ViewBag.UserList 是下拉列表的选项

放置

。如果需要设置下拉菜单的选定值

  

下拉控件名称和ViewBag名称与未正确绑定的数据相同