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

问题描述

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

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

控制器:-

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

感谢您的帮助.

推荐答案

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

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

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

10-29 06:53