Question

I need to choose my spark master layout every time a request for a page is made. I attempted to so this by setting a ViewBag.Layout value in OnActionExecutingand referencing this value in the master layout ref.

<use master="${ViewBag.Layout}"/>

However, this doesn't work, it seems as if spark is not treating the code within the brackets not as code, but as a string. I get the following error:

The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Home/Index.aspx
~/Views/Home/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/Home/Index.cshtml
~/Views/Home/Index.vbhtml
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml
Layouts\${ViewBag.Layout}.spark
Shared\${ViewBag.Layout}.spark

Can anyone tell me why this is? Or point me to an alternative way of doing this?

Was it helpful?

Solution

The layout cannot be dynamically selected using code syntax. The reason for this is that that layout is selected prior to any rendering taking place in the engine. So first the layout is located, and then the engine tries to render all the variables in place. Using a variable for the layout means that the rendering engine doesn't know which file to open.

OTHER TIPS

Actually. it is possible.. Instead of using the code example. Use a ResultFilter.

public void OnResultExecuting(ResultExecutingContext filterContext) {
        var viewResult = filterContext.Result as ViewResult;
        if (viewResult == null)
            return;

        var layoutFile = viewResult.ViewBag.Layout; //the variable you set in your action executing,

        viewResult.MasterName = layoutFile;

    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top