具有键"Survey_Group"的ViewData项目的类型为"System.String",但必须类型为"IEnumerable< SelectListItem>" [英] The ViewData item that has the key 'Survey_Group' is of type 'System.String' but must be of type 'IEnumerable<SelectListItem>'

查看:83
本文介绍了具有键"Survey_Group"的ViewData项目的类型为"System.String",但必须类型为"IEnumerable< SelectListItem>"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i have binded the value from db to the dropdownlist. But when i try to submit in view, it shows :

具有键"Survey_Group"的ViewData项的类型为"System.String",但必须为"IEnumerable"类型.

The ViewData item that has the key 'Survey_Group' is of type 'System.String' but must be of type 'IEnumerable'.

任何人都可以引导我吗?谢谢.

Anyone can guide me? Thanks.

型号:

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

推荐答案

在POST方法中,当模型无效时,您将返回视图,但尚未为 ViewBag.GroupList 分配值(您在 DropDownListFor()方法中使用),因此它为null,因此是例外.

In your POST method, when the model is invalid, you return the view, but have not assigned a value to ViewBag.GroupList (which you use in the DropDownListFor() method) so its null, hence the exception.

您需要在POST方法中

In the POST method you need

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

这篇关于具有键"Survey_Group"的ViewData项目的类型为"System.String",但必须类型为"IEnumerable< SelectListItem>"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆