我已将db中的值绑定到下拉列表。 但是,当我尝试在视图中提交时,它会显示:
具有键' Survey_Group'的ViewData项目。是类型的 ' System.String'但必须属于' IEnumerable'。
任何人都可以指导我吗?感谢。
型号:
[MaxLength(100)]
[DisplayName("Owner Groups")]
public string Survey_Group { get; set; }
查看:
@Html.LabelFor(model => model.Survey_Group, "Owner Groups")
@Html.DropDownListFor(model => model.Survey_Group, (SelectList)ViewBag.GroupList)
控制器:
public ActionResult SURV_Main_Create()
{
ViewBag.CurrentPage = "create";
var model = new SURV_Main_Model();
ViewBag.GroupList = new SelectList(db.SURV_Group_Model, "Group_ID", "GroupName");
return View(model);
}
// POST: /SURV_Main/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SURV_Main_Create(SURV_Main_Model surv_main_model)
{
if (ModelState.IsValid)
{
var r = new Random();
int randomno = r.Next(1, 1000000);
surv_main_model.Survey_Key = "SURV" + DateTime.Now.ToString("yyyyMMddHHmmss") + randomno;
surv_main_model.Survey_Creator = User.Identity.Name;
db.SURV_Main_Model.Add(surv_main_model);
db.SaveChanges();
return RedirectToAction("SURV_Main_Edit", new { id = surv_main_model.Survey_ID });
}
return View(surv_main_model);
}
答案 0 :(得分:2)
在你的POST方法中,当模型无效时,你返回视图,但没有为ViewBag.GroupList
(你在DropDownListFor()
方法中使用)赋值,所以它为null,因此异常。
在POST方法中,您需要
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SURV_Main_Create(SURV_Main_Model surv_main_model)
{
if (ModelState.IsValid)
{
....
}
ViewBag.GroupList = new SelectList(db.SURV_Group_Model, "Group_ID", "GroupName"); // add this
return View(surv_main_model);
}