Cannot Convert Int to String - MVC Dropdownlist Nightmare
So I struggled with this simple code for binding a dropdownlist
IEnumerable items = db.SiteMenus
.Select(c => new SelectListItem { Value = c.MenuID, Text = c.MenuName });
ViewBag.SiteMenuItems = items;
return View();
.Select(c => new SelectListItem {
Value = c.MenuID,
Text = c.MenuName });
ViewBag.SiteMenuItems = items;
return View();
list.Add(new SelectListItem { Text = "-Select Category-", Value = "0" });
var cat = (from c in db.SiteMenus select c).ToArray();
for (int i = 0; i < cat.Length; i++)
{
list.Add(new SelectListItem
{
Text = cat[i].MenuName,
Value = cat[i].MenuID.ToString(),
});
}
ViewBag.SiteMenuItems = list;
List list = new List();
list.Add(new SelectListItem { Text = "-Select Category-", Value = "0" });
var cat = (from c in db.SiteMenus select c).ToArray();
for (int i = 0; i < cat.Length; i++)
{
list.Add(new SelectListItem
{
Text = cat[i].MenuName,
Value = cat[i].MenuID.ToString(),
});
}
ViewBag.SiteMenuItems = list;
return View();
IEnumerable
List
return View();
I had an issue with the Value of the c.MenuID which is a datatype INT and consistently got the error cannot convert int to string. (of course I tried Convert.ToString - to no avail!
Eventually I figured this out - Reference IEnumerable directly in your list
Eventually I figured this out - Reference IEnumerable directly in your list
And Voila - it displayed.
My Razor looks like this:
@Html.DropDownList("MenuID", (IEnumerable) ViewBag.SiteMenuItems,new { MenuID = "MenuID" })
Comments