Home > Blockchain >  How to access HtmlHelper from custom RazorPage type in ASP.NET Core 6?
How to access HtmlHelper from custom RazorPage type in ASP.NET Core 6?

Time:07-28

In ASP.NET MVC 4/5, I used to create my custom WebViewPage to add some methods that I can access from my razor view with a shorter, concise syntax as the following example

public abstract class CustomWebViewPage<TModel> : WebViewPage<TModel>
{
    public string T(string translationKey)
    {
        return Html.Translate(translationKey);
    }
}

In the Razor page, I can use @T instead of @Html.Translate

@T("/path1/path2")

However, in ASP.NET Core 6, I tried to create my custom razor page type (see 2nd screenshot) and found RazorPage type doesn't expose HtmlHelper property, therefore I'm unable to access the inner HtmlHelper like how I did in in traditional ASP.NET MVC 4/5 (see 1st screenshot).

enter image description here

enter image description here

Can someone point me to the right direction?

Thanks

CodePudding user response:

According to the official documentation, WebViewPage<TModel> Class is not applicable to Asp.Net Core 6.

You can use IHtmlHelper to continue to customize HtmlHelper like this:

public static IHtmlContent T(this IHtmlHelper html)
            => new HtmlString("<div> Hello World </div>");

And in Razor Page:

<h1>@Html.T()</h1>

For more details please refer to this link.

CodePudding user response:

If you add this to your project;

<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>

You'll see that your generated pages contain something like;

[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<TModel> Html { get; private set; } = default!;

I think that this property will be injected from HttpContext.RequestServices by RazorPagePropertyActivator.

If you are using @inherits to change the base view class, I don't think you can inject services via a constructor. But you can probably define your own properties with the above [RazorInject] attribute, like the non-generic IHtmlHelper. Or you could resolve the correct service on demand inside a method.

For translation specifically, the asp.net core documentation suggest using the IViewLocalizer service via an explicit injected dependency, which you could add to _ViewImports with a single character variable name. Avoiding the need to create your own base view class.

  • Related