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

狂风中的少年 提交于 2019-12-06 19:53:37

问题


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:

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?

Should I be using a foreach loop to create the select box?


回答1:


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



回答2:


Try this:

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


来源:https://stackoverflow.com/questions/12734782/mvc-net-create-drop-down-list-from-model-collection-in-strongly-typed-view

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