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 decla
I got same error today and my solution is to make model "valid".
In my case, after user submit by clicking "save", I got model state: invalid if user key-in "0", but model state will be valid if user key-in "0.0".
So I override "IsValid" method to return true even user key-in "0".
Hope it helps.
You are setting the collection as an item in ViewData dictionary and trying to retreive it as property on the model. A simple fix would be to reference it the same way as you set it:
<%var basetype = ViewData["basetype"] as IEnumerable<SelectListItem>;%>
<div class="editor-label">
<%: Html.Label("basetype") %>
</div>
<div class="editor-field">
<%: Html.DropDownList("basetype", basetype) %>
<%: Html.ValidationMessage("basetype") %>
</div>
Alternatively, the below code uses a strongly typed view:
public class ViewModel {
//Model properties
public IEnumerable<SelectListItem> basetype {get;set;}
}
public ActionResult Create()
{
var db = new DB();
IEnumerable<SelectListItem> basetypes = db.Basetypes.Select(b => new SelectListItem { Value = b.basetype, Text = b.basetype });
return View(new ViewModel { basetype=basetypes });
}
Then, in your strongly typed view:
<div class="editor-label">
<%: Html.LabelFor(model => model.basetype) %>
</div>
<div class="editor-field">
<%: Html.DropDownListFor(model=>model.basetype) %>
<%: Html.ValidationMessageFor(model => model.basetype) %>
</div>
If you use Html.DropDownList()
method - same error may occur, if your ViewData/Viewbag item not set, as @Peto answered.
But it may be not set in case of controller set item correctly, but in main view you use partial viw call with new ViewDataDictionary values.
if you have @Html.Partial("Partianame", Model,new ViewDataDictionary() { /* ... */ })
then your partial view will not see ViewData
and ViewBag
data, remove new ViewDataDictionary()
parameter
You will receive this error if the SelectList is null.
I've just come across this issue and this article helped me through it - http://odetocode.com/Blogs/scott/archive/2010/01/18/drop-down-lists-and-asp-net-mvc.aspx
The most likely cause it that your collection is repopulated after the po
To future readers,
I came across with the problem today and couldn´t fix it. It turned to be really simple after all. I was working with a table + view. When I updated the table (added a few colums) I forgot to update (drop and recreate) the view, which caused the problem for me. Hope it helps somebody.