具有键“MaritalStatus”的ViewData项的类型为“System.String”,但必须是“IEnumerable <selectlistitem>”类型</selectlistitem>

时间:2013-02-05 05:38:14

标签: asp.net-mvc razor

我正在从内存数据填充DropDownList并在POST上收到此错误。

  

错误:具有键'MaritalStatus'的ViewData项的类型为'System.String',但必须是'IEnumerable'类型。

控制器: -

// GET: /Application/Create
public ActionResult Create()
{
    List<SelectListItem> lst = new List<SelectListItem>();
    lst.Add(new SelectListItem { Text = "Unmarried", Value = "1" });
    lst.Add(new SelectListItem { Text = "Married", Value = "2" });
    lst.Add(new SelectListItem { Text = "Widow", Value = "3" });
    ViewBag.MaritalStatus = new SelectList(lst, "Value", "Text");

    return View();
}

// POST: /Application/Create
[HttpPost]
public ActionResult Create(ApplicationForm applicationform)
{
    if (ModelState.IsValid)
    {
        db.ApplicationForms.Add(applicationform);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(applicationform);
}

查看: -

<div class="editor-label">
    @Html.LabelFor(model => model.MaritalStatus)
</div>
<div class="editor-field">
    @Html.DropDownList("MaritalStatus")
    @Html.ValidationMessageFor(model => model.MaritalStatus)
</div>

模型属性: -

[DisplayName("Marital Status")]
public string MaritalStatus { get; set; }

感谢任何帮助。

1 个答案:

答案 0 :(得分:4)

好吧,我通过在POST操作中重新填充List来解决这个问题,这是完整的工作代码。

    //
    // GET: /Application/Create

    public ActionResult Create()
    {
        List<SelectListItem> lst = new List<SelectListItem>();
        lst.Add(new SelectListItem { Text = "Unmarried", Value = "Unmarried" });
        lst.Add(new SelectListItem { Text = "Married", Value = "Married" });
        lst.Add(new SelectListItem { Text = "Widow", Value = "Widow" });
        ViewBag.MaritalStatus = new SelectList(lst, "Value", "Text");

        return View();
    }

    //
    // POST: /Application/Create

    [HttpPost]
    public ActionResult Create(ApplicationForm applicationform)
    {
        if (ModelState.IsValid)
        {
            db.ApplicationForms.Add(applicationform);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        else
        {
            List<SelectListItem> lst = new List<SelectListItem>();
            lst.Add(new SelectListItem { Text = "Unmarried", Value = "1" });
            lst.Add(new SelectListItem { Text = "Married", Value = "2" });
            lst.Add(new SelectListItem { Text = "Widow", Value = "3" });
            ViewBag.MaritalStatus = new SelectList(lst, "Value", "Text");
        }

        return View(applicationform);
    }