我正在嘗試使用MVC4提交表單,並且似乎無法弄清爲什麼在提交後出現錯誤。我粘貼了以下所有相關代碼以及我所看到的錯誤。MVC中dropdownlistfor的問題
錯誤:
The ViewData item that has the key 'Group' is of type 'System.String' but must be of type 'IEnumerable<SelectListItem>'.
控制器:
[HttpGet]
public ActionResult CreateRole()
{
var RM = new myModel();
RM.Groups = RM.InitializeGroupList();
return View(RM);
}
[HttpPost]
public ActionResult Myfunction(myModel model)
if (ModelState.IsValid)
{
//Execute Update
}
型號:
[Required]
[Display(Name = "Group")]
public string Group { get; set; }
public IEnumerable<SelectListItem> Groups;
public IEnumerable<SelectListItem> InitializeGroupList()
{
List<SelectListItem> topOfList = new List<SelectListItem>
{
new SelectListItem { Value = string.Empty, Text = "Category" },
new SelectListItem { Value = "Administrator", Text = "Administrator" },
new SelectListItem { Value = "Partner", Text = "Partner" },
new SelectListItem { Value = "Internal", Text = "Internal" }
};
//IEnumerable<SelectListItem> list = db.GetRoleList(topOfList);
IEnumerable<SelectListItem> list = topOfList;
return new SelectList(list, "Value", "Text");
}
[Required]
[Display(Name = "Group")]
public string Group { get; set; }
public IEnumerable<SelectListItem> Groups;
查看:
@Html.DropDownListFor(model => model.Group, Model.Groups)
不確定它是否重要,但您可能希望使用「組」作爲屬性替代字段。即添加一個getter和setter:'public IEnumerable Groups {get;組; }' –