C# – Pass Additional ViewData to a Strongly-Typed Partial View

asp.netasp.net-mvcasp.net-mvc-partialviewcviewdata

I have a strongly-typed Partial View that takes a ProductImage and when it is rendered I would also like to provide it with some additional ViewData which I create dynamically in the containing page. How can I pass both my strongly typed object and my custom ViewData to the partial view with the RenderPartial call?

var index = 0;
foreach (var image in Model.Images.OrderBy(p => p.Order))
{
  Html.RenderPartial("ProductImageForm", image); // < Pass 'index' to partial
  index++;
}

Best Answer

RenderPartial takes another parameter that is simply a ViewDataDictionary. You're almost there, just call it like this:

Html.RenderPartial(
      "ProductImageForm", 
       image, 
       new ViewDataDictionary { { "index", index } }
); 

Note that this will override the default ViewData that all your other Views have by default. If you are adding anything to ViewData, it will not be in this new dictionary that you're passing to your partial view.

Related Topic