If MVC only allows you to have one ViewModel per View, how does one incorporate a dropdownlist (need to have a separate ViewModel for this) into an existing View which is already used by another ViewModel (ie an entity which has a column for this dropdownlist)?
-
2Why in the world would you think a drop down list requires a separate view model? – Erik Funkenbusch Jul 27 '13 at 18:51
2 Answers
This Question in addition, I guess, Got everything you are looking for:
How to write a simple Html.DropDownListFor()?
As a beginner, I did a very basic implementation of dropDownlist using the NorthWind Database only.
I had imported the Product & Suppliers table from Northwind database.
In the ProductController.cs
file, which is the controller file for my Product
table, add method: GetAllSuppliers
to get all SuppliersID which we will display in a dropdown.
public IEnumerable<int> GetAllSuppliers()
{
NorthwindEntities db = new NorthwindEntities();
return db.Suppliers.Select(e => e.SupplierID);
}
Now, in the Create
action method in ProductController.cs
, pass all the values of SupplierID
in ViewData
as seen below:
public ActionResult Create()
{
ViewData["Suppliers"] = new SelectList(GetAllSuppliers());
return View(new Product());
}
In your corresponding Create.aspx View
, use this:
<%: Html.DropDownListFor(model => model.SupplierID, ViewData["Suppliers"] as SelectList) %>
Below is a snapshot of the Result:
Let me know if you need any explanation.
-
Thank you! The basic implementation was what i was looking for. Worked for me nicely!! – D Simm Oct 13 '15 at 09:22
You can make a property inside your main ViewModel which contains ViewModel for dropdownlist and use it with dropdown.
Assume you have controller.
public class HomeController
{
public ActionResult Index()
{
var viewModel = new MainViewModel
{
SomeProperty = "SomeValue",
DropDownData = new DropDownDataViewModel() // Initialize it with appropriate data here.
};
return this.View(viewModel);
}
}
And MainViewModel
public class MainViewModel
{
public string SomeProperty {get; set;}
public DropDownDataViewModel DropDownData { get; set; }
}
So, inside your view you can call @Model.DropDownData
to get access to this viewmmodel.

- 3,281
- 20
- 33
-
AlexK, got the idea, but could you provide a simple code snippet example? – sagesky36 Jul 27 '13 at 17:11