MVC .NET Create Drop Down List from Model Collecti

2019-04-21 15:27发布

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?

2条回答
2楼-- · 2019-04-21 15:48

Try this:

<%= Html.DropDownList("SomeName", new SelectList(Model, "orgID", "orgName"), "Please select Organization") %>
查看更多
一夜七次
3楼-- · 2019-04-21 15:55

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")) %>
查看更多
登录 后发表回答