我是 ASP.NET MVC 的新手,如果对我的问题有任何帮助,我将不胜感激。我已经就此主题进行了大量研究(显然还不够)。我需要将下拉列表绑定(bind)到表中的特定列,然后在 View 中呈现它。我已经有了在 Controller 中检索表的查询:
public ActionResult SelectAccountEmail()
{
var queryAccountEmail = (from AccountEmail in db.UserBases select AccountEmail)
var selectItems = new SelectList(queryAccountEmail);
return View(selectItems);
}
在将查询绑定(bind)到 View 中的下拉列表时,我迷路了。
@model RecordUploaderMVC4.Models.UserBase
@{
ViewBag.Title = "SelectAccountEmail";
}
<h2>SelectAccountEmail</h2>
@Html.LabelFor(model => model.AccountEmail);
@Html.DropDownList(Model.AccountEmail);
@Html.ValidationMessageFor(model => model.AccountEmail);
<input /type="submit" value="Submit">
运行时出现错误:
Server Error in '/' Application.
--------------------------------------------------------------------------------
The model item passed into the dictionary is of type 'System.Web.Mvc.SelectList', but this dictionary requires a model item of type 'RecordUploaderMVC4.Models.UserBase'.
任何帮助将不胜感激。
提前致谢。
最佳答案
很少有错误。首先,更改您的模型以添加以下属性(查看您的 View ,它是 RecordUploaderMVC4.Models.UserBase
):
public class UserBase
{
public string AccountEmail { get; set; }
public SelectList Emails { get; set; }
//rest of your model
}
然后,在 Controller 中正确构建模型:
public ActionResult SelectAccountEmail()
{
UserBase model = new UserBase();
var queryAccountEmail = (from AccountEmail in db.UserBases select AccountEmail)
model.Emails = new SelectList(queryAccountEmail);
return View(model);
}
然后在你看来你可以这样做:
@Html.LabelFor(model => model.AccountEmail)
@Html.DropDownListFor(model => model.AccountEmail, Model.Emails)
@Html.ValidationMessageFor(model => model.AccountEmail)
关于c# - 使用 ASP.NET MVC4 将 View 中的 DropDownList 绑定(bind)到表中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15688074/