在渲染时动态选择火花主布局

时间:2012-02-02 11:17:16

标签: c# model-view-controller spark-view-engine

每次发出页面请求时,我都需要选择我的spark主布局。我尝试通过在ViewBag.Layout中设置OnActionExecuting值并在主布局参考中引用此值来尝试这样做。

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

但是,这不起作用,似乎spark不会将括号内的代码视为代码,而是作为字符串。我收到以下错误:

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

谁能告诉我为什么会这样?或者指出另一种方法吗?

2 个答案:

答案 0 :(得分:1)

无法使用代码语法动态选择布局。这样做的原因是在引擎中进行任何渲染之前选择了该布局。首先定位布局,然后引擎尝试渲染所有变量。使用变量进行布局意味着渲染引擎不知道要打开哪个文件。

答案 1 :(得分:0)

实际上。它是可能的..而不是使用代码示例。使用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;

    }