Replacement for @helper in ASP.NET Core

后端 未结 8 1550
傲寒
傲寒 2020-11-30 06:35

So far, i don\'t think ViewComponent solves that neither does TagHelper. Is there any replacement to this? Something that takes parameters and retu

8条回答
  •  时光取名叫无心
    2020-11-30 07:07

    I'd like to expand on @Alexaku's answer and show how I've implemented a helper like function. It's only useful on one specific page but it allows you to execute a piece of razor code multiple times with input parameters. The syntax is not great but I've found it very useful in the absence of razor's @helper function. First declare some kind of Dto that will contain the input parameters into the function.

    @functions {
       private class Dto
       {
          public string Data { get;set; }
       }
    }
    

    Then declare the razor function. Note that the displayItem value can be multi-line and also note that you access the Dto variable using the @item.

    @{
       Func displayItem = @@item.Data;
    }
    

    Then when you want to use the razor template you can call it like the following from anywhere in the page.

    @displayItem(new Dto {Data = "testingData1" });
    @displayItem(new Dto {Data = "testingData2" });

提交回复
热议问题