0

我想使用这样的自定义视图引擎来操作 HTML:

protected override void RenderView(ViewContext viewContext, TextWriter writer, object instance)
{
    if (viewContext.Controller is MyController)
    {
       .. alter the html then write to writer
    } else {
        base.RenderView(viewContext, writer, instance);
    }
}

RenderView被调用视图和每个部分视图,但我无法找到一种可靠的方法来确定它是渲染外部视图还是部分视图。

writer对象的类型是HttpWriter局部视图和StringWriter外部视图。这似乎是一种不好的测试方法,但到目前为止,这是我能找到的唯一具体的东西

告诉我instance视图或局部视图名称,但检查字符串以查看我是否正在渲染局部视图似乎很脆弱。

有没有更直接的方法来确定它是否是部分视图?

4

1 回答 1

0

您可以从自定义视图引擎将布尔参数传递给自定义视图:

public class MyRazorView : RazorView
{
    private readonly bool _isPartial;

    public MyRazorView(ControllerContext controllerContext, string viewPath, string layoutPath, bool runViewStartPages, IEnumerable<string> viewStartFileExtensions, IViewPageActivator viewPageActivator, bool isPartial)
        : base(controllerContext, viewPath, layoutPath, runViewStartPages, viewStartFileExtensions, viewPageActivator)
    {
        _isPartial = isPartial;
    }

    protected override void RenderView(ViewContext viewContext, TextWriter writer, object instance)
    {
        if (viewContext.Controller is MyController)
        {
            if (_isPartial)
            {
                // it's a partial
            }
            else
            {
                // it's the main view
            }
        } 
        base.RenderView(viewContext, writer, instance);
    }
}

public class MyRazorViewEngine : RazorViewEngine
{
    protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
    {
        return new MyRazorView(
            controllerContext, 
            partialPath, 
            null, 
            false, 
            base.FileExtensions, 
            base.ViewPageActivator, 
            true
        );
    }

    protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
    {
        return new MyRazorView(
            controllerContext, 
            viewPath, 
            masterPath, 
            true, 
            base.FileExtensions, 
            base.ViewPageActivator, 
            false
        );
    }
}
于 2012-06-28T16:03:18.290 回答