我想使用像这样的自定义视图引擎来操作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
告诉我视图或部分视图名称,但检查字符串以查看我是否渲染部分视图似乎很脆弱。
有没有更直接的方法来确定它是否是部分视图?
答案 0 :(得分: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
);
}
}