【问题标题】:The ViewData item that has the key 'Survey_Group' is of type 'System.String' but must be of type 'IEnumerable<SelectListItem>'具有键“Survey_Group”的 ViewData 项属于“System.String”类型,但必须属于“IEnumerable<SelectListItem>”类型
【发布时间】:2015-09-18 12:18:45
【问题描述】:

我已将 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);
}

【问题讨论】:

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


    【解决方案1】:

    在您的 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);
    }
    

    【讨论】:

      猜你喜欢
      • 2012-05-23
      • 2013-01-19
      • 2017-01-22
      • 2016-03-25
      • 2016-03-21
      • 2014-11-13
      • 2023-03-12
      相关资源
      最近更新 更多