C# MVC .NET 在强类型视图中从模型集合创建下拉列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12734782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MVC .NET Create Drop Down List from Model Collection in Strongly Typed view
提问by Colin Pear
So I have a view typed with a collection like so:
所以我有一个像这样的集合类型的视图:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IList<DTO.OrganizationDTO>>" %>
The OrganizationDTO looks like this:
OrganizationDTO 看起来像这样:
public OrganizationDTO
{
int orgID { get; set; }
string orgName { get; set; }
}
I simply want to create a Drop Down List from the collection of OrganizationDTO's using an HTML helper but for the life of me I cant figure it out! Am I going about this the wrong way?
我只是想使用 HTML 帮助程序从 OrganizationDTO 的集合中创建一个下拉列表,但在我的一生中我无法弄清楚!我会以错误的方式解决这个问题吗?
Should I be using a foreach loop to create the select box?
我应该使用 foreach 循环来创建选择框吗?
采纳答案by Johan Lundqvist
I did a small example, with a model like yours:
我做了一个小例子,有一个像你这样的模型:
public class OrganizationDTO
{
public int orgID { get; set; }
public string orgName { get; set; }
}
and a Controller like:
和一个控制器,如:
public class Default1Controller : Controller
{
//
// GET: /Default1/
public ActionResult Index()
{
IList<OrganizationDTO> list = new List<OrganizationDTO>();
for (int i = 0; i < 10; i++)
{
list.Add(new OrganizationDTO { orgID = i, orgName = "Org " + i });
}
return View(list);
}
}
and in the view:
并在视图中:
<%= Html.DropDownListFor(m => m.First().orgID, new SelectList(Model.AsEnumerable(), "orgId","orgName")) %>
回答by webdeveloper
Try this:
尝试这个:
<%= Html.DropDownList("SomeName", new SelectList(Model, "orgID", "orgName"), "Please select Organization") %>

