The ViewData item that has the key 'MY KEY' is of type 'System.String' but must be of type 'IEnumerable<SelectListItem>'.
Posted
by
JBibbs
on Stack Overflow
See other posts from Stack Overflow
or by JBibbs
Published on 2010-08-03T04:09:39Z
Indexed on
2011/06/28
16:22 UTC
Read the original article
Hit count: 528
asp.net-mvc
I am trying to populate a dropdown list from a database mapped with Linq 2 SQL, using ASP.NET MVC 2, and keep getting this error.
I am so confused because I am declaring a variable with the type IEnumerable<SelectListItem> on the second line, but the error makes me think this is not the case. I feel like this should be very simple, but I am struggling. Any help is appreciated.
Here are the interesting bits of my controller:
public ActionResult Create()
{
var db = new DB();
IEnumerable<SelectListItem> basetypes = db.Basetypes.Select(b => new SelectListItem { Value = b.basetype, Text = b.basetype });
ViewData["basetype"] = basetypes;
return View();
}
And here are the interesting bits of my view:
<div class="editor-label">
<%: Html.LabelFor(model => model.basetype) %>
</div>
<div class="editor-field">
<%: Html.DropDownList("basetype") %>
<%: Html.ValidationMessageFor(model => model.basetype) %>
</div>
Here is the Post action when submitting the Form
// POST: /Meals/Create
[HttpPost]
public ActionResult Create(Meal meal)
{
if (ModelState.IsValid)
{
try
{
// TODO: Add insert logic here
var db = new DB();
db.Meals.InsertOnSubmit(meal);
db.SubmitChanges();
return RedirectToAction("Index");
}
catch
{
return View(meal);
}
}
else
{
return View(meal);
}
}
Thanks.
© Stack Overflow or respective owner