ASP.NET MVC3 Razor - create view from a string?

前端 未结 1 697
庸人自扰
庸人自扰 2021-01-14 19:24

Is there a convenient way to return a view from a string instead of having to come from a file on disk?

I\'ve implemented a custom VirtualPathProvider t

1条回答
  •  不知归路
    2021-01-14 19:50

    You can run the view yourself by creating a RazorTemplateEngine which reads your source and compiles into a WebViewPage.

    You can then run the WebViewPage by writing

    webViewPage.OverridenLayoutPath = LayoutPath;
    webViewPage.VirtualPath = ViewPath;
    webViewPage.ViewContext = viewContext;
    webViewPage.ViewData = viewContext.ViewData;
    
    webViewPage.InitHelpers();
    WebPageRenderingBase startPage = null;
    if (RunViewStartPages) {
        startPage = StartPageLookup(webViewPage, RazorViewEngine.ViewStartFileName, ViewStartFileExtensions);
    }
    webViewPage.ExecutePageHierarchy(new WebPageContext(context: viewContext.HttpContext, page: null, model: null), writer, startPage);
    

    To support the new @model keyword, you'll need to override methods in your RazorEngineHost to use MVC's custom generators:

    public override RazorCodeGenerator DecorateCodeGenerator(RazorCodeGenerator incomingCodeGenerator) {
        if (incomingCodeGenerator is CSharpRazorCodeGenerator) {
            return new MvcCSharpRazorCodeGenerator(incomingCodeGenerator.ClassName,
                                                   incomingCodeGenerator.RootNamespaceName,
                                                   incomingCodeGenerator.SourceFileName,
                                                   incomingCodeGenerator.Host);
        }
        else if (incomingCodeGenerator is VBRazorCodeGenerator) {
            return new MvcVBRazorCodeGenerator(incomingCodeGenerator.ClassName,
                                               incomingCodeGenerator.RootNamespaceName,
                                               incomingCodeGenerator.SourceFileName,
                                               incomingCodeGenerator.Host);
        }
        return base.DecorateCodeGenerator(incomingCodeGenerator);
    }
    
    public override ParserBase DecorateCodeParser(ParserBase incomingCodeParser) {
        if (incomingCodeParser is CSharpCodeParser) {
            return new MvcCSharpRazorCodeParser();
        }
        else if (incomingCodeParser is VBCodeParser) {
            return new MvcVBRazorCodeParser();
        }
        else {
            return base.DecorateCodeParser(incomingCodeParser);
        }
    }
    

    0 讨论(0)
提交回复
热议问题