I'm trying to write a html helper extension that outputs an image tag. I need to access (within C# code) something like Razor's @Url.Content() helper to get the proper URL for the current context. How does one do this?
Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine. You can use it anywhere to generate output like HTML. It's just that ASP.NET MVC has implemented a view engine that allows us to use Razor inside of an MVC application to produce HTML.
Razor is a templating engine and ASP.NET MVC has implemented a view engine which allows us to use Razor inside of an MVC application to produce HTML. However, Razor does not have any ties with ASP.NET MVC. Now, Razor Syntax is compact which minimizes the characters to be used, however it is also easy to learn.
Razor supports C# and uses the @ symbol to transition from HTML to C#. Razor evaluates C# expressions and renders them in the HTML output. When an @ symbol is followed by a Razor reserved keyword, it transitions into Razor-specific markup.
Razor pages have handler-methods which are HTTP verbs. So to call a method from your page you need to put On followed by the http verb you want then your method name . And in your view pass the name to the asp-page-handler without the OnPost or OnGet prefix or Async suffix.
Use the following to mimic Url.Content in code.
VirtualPathUtility.ToAbsolute("~/url/");
You can create your own instance of UrlHelper
by passing in the appropriate ViewContext
. For example, to do this from an image helper:
public static string CustomImage(this HtmlHelper html) { var Url = new UrlHelper(html.ViewContext.RequestContext); }
At this point you can call Url.Content()
or any other UrlHelper
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With