如何从RazorViewEngine中创建的IView访问WebViewPage实例?

时间:2015-02-28 11:51:56

标签: c# asp.net-mvc razor

在我的网络MVC应用程序中,我定义了一个自定义RazorViewEngine,如下所示:

    public class MyRazorEngine : RazorViewEngine
    {
        protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
        {
            var tmp = base.CreateView(controllerContext, viewPath, masterPath);

            // *** here some action i want do by (tmp as MyWebPageBase).
            // *** for example access to the 'SomeField' value which assigned into (tmp as MyWebPageBase).

            return tmp;

        }
   }

我定义了继承MyWebViewPage.cs的视图:

public abstract class MyWebViewPage<TModel> : System.Web.Mvc.WebViewPage<TModel>
{
    public int SomeField{ get; set;};
}

现在,我的问题是我无法从MyWebPageBase类专门访问呈现的视图RazorViewEngine。怎么办?

1 个答案:

答案 0 :(得分:1)

这取决于你想要做什么。

base.CreateView(controllerContext, viewPath, masterPath) 

返回IView,而System.Web.Mvc.WebViewPage未实现IView,因此您无法在它们之间进行转换,而且无论如何都会在管道中进行转换。

你可以继承RazorView并覆盖RenderView方法,因为你可以在下面看到它在它的实例参数中传递了一个WebViewPage但是对于你想要做的任何事情来说这可能为时已晚:

  protected override void RenderView(ViewContext viewContext, TextWriter writer, object instance)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }

            WebViewPage webViewPage = instance as WebViewPage;
            if (webViewPage == null)
            {
                throw new InvalidOperationException(
                    String.Format(
                        CultureInfo.CurrentCulture,
                        MvcResources.CshtmlView_WrongViewBase,
                        ViewPath));
            }

或者您可以实现自己的IViewPageActivator并将其插入解析器:

public interface IViewPageActivator {
    object Create(ControllerContext controllerContext, Type type);
}

Brad Wilson introduces that here : View Page Activator