问题
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);
}
来源:https://stackoverflow.com/questions/14700861/the-viewdata-item-that-has-the-key-maritalstatus-is-of-type-system-string-bu