DropDownListFor without foreach in ASP.NET MVC 3

一曲冷凌霜 提交于 2019-12-12 04:32:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!