Jana Weschenfelder Jana Weschenfelder - 1 year ago 102
C# Question

How can I save multiple ViewModels in ASP.NET MVC 4?

I followed the instructions of the article http://www.codeproject.com/Tips/850816/Dynamically-Populate-Dependent-Dropdown-List-in-MV for an own project. It works fine. I can dynamically populate dependent dropdownlists in this way.

The code in "5.4 Update Index View" of the article above unifies the ViewModels CityViewModel, StateProvinceViewModel and CountryViewModel. Every ViewModel contains the information for its own dropdownlist.

My question is now:

How can I save the current selections in all three dropdownlists after the selections were made? (I want to save the currently selected values in the dropdownlists in a database). Can someone give me a hint, please?
I know how to handle one ViewModel (maybe with three different DataModels), but I don't know where to start if multiple ViewModels are used.

I use C# and Razor (but I'm also able to read VB and to translate VB into C#). As far as I know, I can only save one ViewModel, or am I wrong?

Answer Source

How can I save the current selections in all three dropdownlists after the selections were made?

Sounds like you may need a Ajax callback to a controller action after each dropdown change event? In effect (to demonstrate the basics)

Have a look at this MVC Fiddle


Assuming we have a bunch of dropDown lists on a page:

<form id="theForm">
    @Html.DropDownListFor(m => m.DropDown1, new SelectList(this.Model.DropDown1Items), new { @class="ddl"} )
    @Html.DropDownListFor(m => m.DropDown2, new SelectList(this.Model.DropDown2Items), new { @class="ddl"} )
    @Html.DropDownListFor(m => m.DropDown3, new SelectList(this.Model.DropDown3Items), new { @class="ddl"} )

How you select the values to save can be dependent on a JQuery selector (in this case the css class .ddl

                    $.post('@Url.Action("Save", "Home")', 
                        $(".ddl").serialize(), function(c)


Just make sure you have an action method to collect this information, and ensure the parameter names of the action method match the field names what will be within the HTTP Post. (Fiddler or Firebug of Chrome developer tools can show you these if they are not clear)

public JsonResult Save(string dropDown1, string dropDown2, string dropDown3)
    // do save logic here
    return Json("Saved: " + dropDown1 + " " + dropDown2 + " " + dropDown3);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download