Extension Method and Razor Page

I defined an extension method in app_code as shown below.

public static class Extensions { public static string Hi(this object obj) { return "hi"; } } 

On the razor page everything can say Hi :)

 @Html.Hi(); @Request.Hi(); @this.Hi(); 

But @Hi() not working. Is there any way to make @Hi() ?

+4
source share
3 answers

C # only allows calling extension methods defined by an instance of an object.
If you have an extension method that extends your type, you cannot call it "directly"; you need to write this.ExtensionMethod() .

The only way to do what you ask is to create a class that inherits WebPage (or WebViewPage for MVC views) and change the Razor page to inherit this class (using the @inherits directive)

+5
source

I do not think you can only call @Hi (). Pretty sure there should be @ this.Hi ()

+1
source

As a normal scenario, you should include it in use. synthase razor

 @using Namespace.Namespace 
0
source

Source: https://habr.com/ru/post/1339923/


All Articles