Jana Weschenfelder Jana Weschenfelder - 3 months ago 18
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

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

https://dotnetfiddle.net/JCwltD

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"} )
</form>

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

$(document).ready(function()
            {
                $(".ddl").change(function()
                {
                    $.post('@Url.Action("Save", "Home")', 
                        $(".ddl").serialize(), function(c)
                        {
                            alert(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)

[HttpPost]
public JsonResult Save(string dropDown1, string dropDown2, string dropDown3)
{           
    // do save logic here
    return Json("Saved: " + dropDown1 + " " + dropDown2 + " " + dropDown3);
}