简体   繁体   English

MVC .NET在强类型视图中从模型集合创建下拉列表

[英]MVC .NET Create Drop Down List from Model Collection in Strongly Typed view

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! 我只是想使用HTML助手从OrganizationDTO的集合中创建一个下拉列表,但对于我的生活,我无法弄明白! Am I going about this the wrong way? 我是以错误的方式来做这件事的吗?

Should I be using a foreach loop to create the select box? 我应该使用foreach循环来创建选择框吗?

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")) %>

试试这个:

<%= Html.DropDownList("SomeName", new SelectList(Model, "orgID", "orgName"), "Please select Organization") %>

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

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