I have the following action method which contains the ViewBag:
public ActionResult Method()
{
var model = new PropertyDto();
if (!Request.Url.AbsoluteUri.Contains("?amp=1"))
{
if (DefaultCityID > 0)
model.CityID = DefaultCityID;
List<SelectListItem> Cities = cityService.GetMenuCitiesLite(1).Select(t => new SelectListItem { Text = t.Name, Value = t.ID.ToString() })
.OrderBy(o=>o.Text).ToList();
ViewBag.Cities = Cities;
ViewBag.CitiesIds = DefaultCityID;
}
ViewBag.Cities = cityService.GetMenuCitiesLite(SiteKeys.CountryID);
return View(model);
}
on the view dropdown list:
@Html.DropDownListFor(model => model.CityID, (List<SelectListItem>)ViewBag.Cities, "Select city", new RouteValueDictionary { { "data-rule-required", "true" }, { "data-msg-required", "*required" }, { "class", "form-control" }, { "id", "CityDropdown" } })
I am getting this exception:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Cannot convert type 'System.Collections.Generic.List<POS.Dto.CityliteDto>' to 'System.Collections.Generic.List<System.Web.Mvc.SelectListItem>''
Just use a SelectList for the ViewBag and Pass to the View
It should be something like
ViewBag.Cities = new SelectList (from t in cityService.OrderBy(o => o.Text)
select New { Description = t.Name, Id = t.ID.ToString() }),"Id","Description");
and then in your View
@Html.DropDownListFor(model => model.CityID, (SelectList)ViewBag.Cities, "Select city", new RouteValueDictionary { { "data-rule-required", "true" }, { "data-msg-required", "*required" }, { "class", "form-control" }, { "id", "CityDropdown" } })
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.