具有键&#39; Survey_Group&#39;的ViewData项。属于&#39; System.String&#39;但必须属于&#39; IEnumerable <selectlistitem>&#39;

时间:2015-07-01 11:12:09

标签: c# asp.net-mvc-4 view

我已将db中的值绑定到下拉列表。 但是,当我尝试在视图中提交时,它会显示:

  

具有键&#39; Survey_Group&#39;的ViewData项目。是类型的   &#39; System.String&#39;但必须属于&#39; IEnumerable&#39;。

任何人都可以指导我吗?感谢。

型号:

[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);
}

1 个答案:

答案 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);
}