Dynamically Loading Partial Views with the Spark View Engine

Loading a partial view is easy with Spark. There are basically two ways:

<use file="MyPartialView" />

And if you have name your files using the _MyPartialView.spark convention:

<MyPartialView />

Now what if you don’t know the name of the partial file until runtime and need to dynamically render the view? As far as I know, there is no way of doing this in Spark. How you can get around this is by doing some inline code using ASP.NET MVCs RenderPartial method.

#Html.RenderPartial( myPartialViewVariable );

This is assuming myPartialViewVariable is a string variable with the name of the view that needs to be rendered.

Update:

When you use ASP.NET’s Html.RenderPartial, your data isn’t automatically passed along to the spark view. To pass your data along, use the ViewData dictionary, like you would in a controller.

<ul>
    <li each="var item in items">
        #ViewData["item"] = item;
        #Html.RenderPartial( "path/to/" + item.Name );
    </li>
</ul>

In the partial view, use the <viewdata /> spark attribute like you normally would in a spark file.

<viewdata item="Item" />

Leave a Reply