populating a DropDownlist in ASP.NET MVC
I'm learning ASP.NET MVC. I had a small problem when dealing with dropdownlist.
This is what I did in controller
List<Int32> myList = new List<Int32>();
var a = (from m in datacontext.services
select m.ServiceID);
myList = a.ToList();
ViewData["ServiceID"] = new SelectList((IEnumerable<SelectListItem>)
a.ToList(), "ServiceID", "ServiceID");
In the view
@Html.DropDownListFor(model => model.ServiceID, ViewData["ServiceID"] as SelectList)
This results in an error
Unable to cast object of type 'System.Collections.Generic.List
1[System.Int32]' to type 'System.Collections.Generic.IEnumerable
1[System.Web.Mvc.SelectListItem]'."
How can this be resolved?
What's the best way to deal with populating dropdownlist开发者_运维技巧 with a query?
There is an error in the cast.
To fix you can do this:
var a = datacontext.services.Select(arg => new { ServiceID = arg.ServiceID }).ToList();
ViewData["ServiceID"] = new SelectList(a, "ServiceID", "ServiceID");
or this:
var a = datacontext.services.Select(arg => arg.ServiceID).ToList();
ViewData["ServiceID"] = new SelectList(a);
In your code a
is the list of integers. It cannot be cast into the list of SelectListItem
.
Side note:
myList
variable is not used in your code.
You need to convert your list of Int32
's into a List/IEnumerable of SelectListItem
's. You are not able to do this as a direct cast (which is what you are trying to do, and what you error represents).
You can adjust your LINQ query to return an IEnumerable<SelectListItem>
by changing the select return type.
var a = (from m in datacontext.services
select new SelectListItem{ Text = m.ServiceID.ToString(), Value = m.ServiceID.ToString() });
you can then load it into a SelectList
via:
ViewData["ServiceID"] = new SelectList(a);
Also, if you have a dropdown list you want populated with text items, you can do the following:
Controller:
public ActionResult Create()
{
var viewModel = new Store();
var storeTypes = new SelectList(
(
from t in _db.StoreTypes
select new SelectListItem
{
Text = t.StoreTypeName,
Value = SqlFunctions.StringConvert((double)t.StoreTypeID) //convert int to string (yikes)
}
)
, "Value", "Text");
ViewData["StoreTypes"] = storeTypes;
return View(viewModel);
}
View:
<div class="class">
<%: Html.DropDownList("StoreTypeID", (SelectList)ViewData["StoreTypes"]) %>
<%--<%: Html.DisplayTextFor(model => model.StoreTypeID) %>--%>
</div>
精彩评论