RazorGenerator can't see custom cshtml helper

前端 未结 5 2168
小鲜肉
小鲜肉 2021-02-12 20:06

I\'m having a problem with RazorGenerator: it can\'t compile views that uses my custom helper:

App_Code/ViewHelper.cshtml

@helper test(System.Web.Mvc.Ht         


        
5条回答
  •  佛祖请我去吃肉
    2021-02-12 21:07

    Solution:

    You need to put this comment at the beginning of a helper you have in App_Code:

    @*
        Generator: MvcHelper
        GeneratePrettyNames : true
    *@
    

    Then in web.config where you have configuration for razor pages you need to add namespace that RazorGenerator generated for those helpers:

    
        
        
                            
                
            
        
    
    

    Change YourWebAppNamespace to you default project namespace (it's probably your project name):


    Explanation:

    RazorGenerator treated you helpers like normal razor view so the generated code looked like this:

        [System.CodeDom.Compiler.GeneratedCodeAttribute("RazorGenerator", "2.0.0.0")]
        [System.Web.WebPages.PageVirtualPathAttribute("~/App_Code/TestHelper.cshtml")]
        public partial class _App_Code_TestHelper_cshtml : Komplett.Chrome.Web.Features.Shared.BaseView
        {
    
    #line 3 "..\..\App_Code\TestHelper.cshtml"
    public System.Web.WebPages.HelperResult HelperName(string name) {
    

    You need to add these directive comments to tell razor generator to create class with "normal" name (the same as helper file name, you do this with GeneratePrettyNames directive) and with static public function so it could be used in other views (done by Generator: MvcHelper directive). With those directive comments RazorGenerator generate C# file like this:

        [System.CodeDom.Compiler.GeneratedCodeAttribute("RazorGenerator", "2.0.0.0")]
        public class TestHelper : System.Web.WebPages.HelperPage
        {
    
    #line 6 "..\..\App_Code\TestHelper.cshtml"
    public static System.Web.WebPages.HelperResult HelperName(string name) {
    

    You now just need to add namespace to web.config so C# generated code for other views would have using statement with namespace of this generated helper.

提交回复
热议问题