Thursday, 3 July 2014

Passing object from view to partial view with ViewDataDictionary in ASP.NET MVC

There might be a situation where you have parent model that for instance hold list of objects that you want to pass to partial view. I prefer to not use View Data or ViewBag and make sure that view models I am using always hold information I want to access, but there might be some exceptions.

Take a look at this example

 @Html.Partial("_EditAddress", Model.AddressVM, new ViewDataDictionary { { "statesList", Model.stateList} })

Third parameter in constructor for Partial class is ViewDataDictionary. Using this we can replace ViewData for partial view.
statesList in this example is key and Model.stateList is data that parent Model holds.

To retrieve the data in partial view access it like you would normally access ViewData and cast it to an object you are expecting.

So for instance if we are using dropdownlist helper :

@Html.DropDownListFor(m => m.stateId, new SelectList(ViewData["statesList"] as List<States>, "stateId", "name", "stateId"), "Select state")