1

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)?

sagesky36
  • 4,542
  • 19
  • 82
  • 130

2 Answers2

3

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:

enter image description here

Let me know if you need any explanation.

Community
  • 1
  • 1
R.C
  • 10,417
  • 2
  • 35
  • 48
1

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.