Saturday, May 06, 2017

In C# .Net MVC, How to Pass Arguments to RenderPartial

Sometimes you just need to pass a bit of extra information to a RenderPartial.  It's easy in Microsoft MVC.  Assuming you need to pass the "name" of a zoo animal for the picture tiles:

Html.RenderPartial("_ZooAnimalTile", Animal);

All you need to do is add an entry to the ViewDataDictionary like this:

Html.RenderPartial("_ZooAnimalTile", Animal, new ViewDataDictionary { { "name",  "Mikey"} });

Then in the "_ZooAnimalTile" partial, you can extract the name like this:

string name= this.ViewData.ContainsKey("name")  && ViewData["name"] != null ? this.ViewData["name"].ToString() : string.Empty;

 Enjoy.  (I know the picture of the meerkat is superfluous, but ... I like meerkats).

PS: We have to be paranoid and check for the presence of "name" (i.e., this.ViewData.ContainsKey("name")  && ViewData["name"] != null) since this partial may be called from different places now or in the future.

No comments: