Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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?

like image 570
Colin Pear Avatar asked Oct 04 '12 19:10

Colin Pear


1 Answers

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")) %>
like image 142
Johan Lundqvist Avatar answered Oct 13 '22 00:10

Johan Lundqvist