问题
ViewCode
public IList<Domain.Entity.Site> Sites { get; set; }
Controller (GetAll return a IList)
newViewModel.Sites = siteRepository.GetAll();
View
@Html.DropDownListFor ?
I need to display a dropdown with some properties of the list items. Id and Url are some properties of these items in the list.
回答1:
It worked!
ViewModel
public IEnumerable<SelectListItem> Sites {get; set;}
public string SiteSelected {get; set;}
Controller
private IEnumerable<SelectListItem> GetAllSites()
{
return context.SITE.Select(x => new SelectListItem
{
Text = x.NAME,
Value = SqlFunctions.StringConvert((double)x.ID).Trim()
}).ToList();
}
siteViewModel.Sites = GetAllSites();
View
@Html.DropDownListFor(model => model.SiteSelected , Model.Sites)
回答2:
See the accepted answer for this question
You need to modify it to appropriately work with an IList
but it is a small code change.
来源:https://stackoverflow.com/questions/6387120/dropdownlistfor-without-foreach-in-asp-net-mvc-3