The ViewData item that has the key 'MaritalSta

2019-07-10 18:54发布

问题:

This question already has an answer here:

  • The ViewData item that has the key 'XXX' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>' 5 answers

I am populating DropDownList from in-memory data and getting this error on POST.

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

Controller:-

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

View:-

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

Model Property:-

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

Any help is appreciated.

回答1:

Well, i solved this by repopulating the List in POST action, here is the complete working code.

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