简体   繁体   English

DropDownListFor没有ASP.NET MVC 3中的foreach

[英]DropDownListFor without foreach in ASP.NET MVC 3

ViewCode ViewCode

public IList<Domain.Entity.Site> Sites { get; set; }

Controller (GetAll return a IList) 控制器(GetAll返回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. Id和Url是列表中这些项目的一些属性。

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)

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. 您需要修改它以适当地使用IList但这是一个小的代码更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM