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

1
  • 2
    Why in the world would you think a drop down list requires a separate view model? Commented Jul 27, 2013 at 18:51

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! The basic implementation was what i was looking for. Worked for me nicely!!
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.

1 Comment

AlexK, got the idea, but could you provide a simple code snippet example?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.