I'm trying to populate a dropdown in my view. Any help is greatly appreciated. Thanks.
Error:
Unable to cast the type 'System.Int32' to type 'System.Object'.
LINQ to Entities only supports casting Entity Data Model primitive types.
Controller:
ViewBag.category = (from c in new IntraEntities().CategoryItems
select new SelectListItem() {Text=c.Name, Value=""+c.ID }).ToList<SelectListItem>();
View:
Category:<br />@Html.DropDownList("category", (List<SelectListItem>)ViewBag.category)
You can cast your query to an .AsEnumerable() prior to the conversion to force it to use Linq to Objects for the casting but it is better to use the SQL compatible functions available in System.Data.Objects.SqlClient.SqlFunctions like so:
(from c in new IntraEntities().CategoryItems
select new SelectListItem() {
Text = c.Name,
Value = SqlFunctions.StringConvert((double)c.ID).TrimStart()
})
How about this:
ViewBag.category =
from c in new IntraEntities().CategoryItems.ToList()
select new SelectListItem
{
Text = c.Name,
Value = c.ID.ToString()
};
and how about using strongly typed view models instead of some weakly typed crap of a ViewBag (it's the way I call it)?
Like this:
public class CategoryViewModel
{
public string CategoryId { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
}
then:
public ActionResult Foo()
{
var model = new CategoryViewModel
{
Categories =
from c in new IntraEntities().CategoryItems.ToList()
select new SelectListItem
{
Text = c.Name,
Value = c.ID.ToString()
}
};
return View(model);
}
and finally in your strongly typed view:
@model CategoryViewModel
@using (Html.BeginForm())
{
@Html.DropDownListFor(x => x.CategoryId, Model.Categories)
<button type="submit">OK</button>
}
Much better, don't you think?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With