Multiple Dropdown Lists, Multiple Models

3.7k Views Asked by At

I have a few entities that I want to fill into a few dropdown lists on a single form. Which is the best way to go about doing so. For multiple models in a single view I've created a viewmodel and threw the entities into it but how can I bring back the list in the database say for entity "Network" and fill the dropdown with "Name" and "NetworkID"?

3

There are 3 best solutions below

0
On

You can do as follows:

Designing your model:

Prepare Select List for as many dropdowns you want

For eg:

Public class ModelName
{
...// Properties
public IEnumerable<SelectListItem> ListName1 { get; set; }
public IEnumerable<SelectListItem> ListName2 { get; set; }
public IEnumerable<SelectListItem> NetWorkList { get; set; }
... //etc
}

Prepare and bind List to Model in Controller :

    public ActionResult Index(ModelName model)
    {
    var networks = // Your network List
    model.NetWorkList = networks.Select(x=> new SelectListItem() {
                Text = x.Name,
                Value = x.NetworkID
           });

    ..// Same as above prepare the list for other dropdowns

    return View(model);
    }

Then in your view prepare your dropdown as follows:

@Html.DropDownListFor(m => Model.NetworkID,Model.NetWorkList)
0
On

Well in that case you can keep all the model list data in somewhere in java script model and then using the JQuery you can bind all of Dropdown controls with same model list.

Alternatively you can fetch that data using Ajax and bind those Dropdowns there in java script and retrieve the value rather then throwing data multiple list from controller.

0
On

First create the Model:

public class Data
    {       
        public List<tbl_Dept> lstDepatrment;
        public List<tbl_employees> lstEmployee; 
        //other
    }

Then just Create a View

@model MVCApp.Models.Data
@{
    var categoryList = Model.lstDepatrment.Select(cl => new SelectListItem
       {
           Value = cl.Dept_ID.ToString(),
           Text = cl.Dept_Description == null ? String.Empty : cl.Dept_Description
       });
     //list for other Drop Down
}
@(Html.DropDownList("sampleDropdown", categoryList, "-----Select-----"))