Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In ASP.NET MVC how can I use the Razor @Url.Content() helper from C# code?

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?

like image 899
JC Grubbs Avatar asked Dec 09 '08 06:12

JC Grubbs


People also ask

Does ASP.NET MVC use Razor?

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.

What is Razor in MVC with example?

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.

What is Razor syntax in C#?

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.

How do I call Razor page?

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.


2 Answers

Use the following to mimic Url.Content in code.

VirtualPathUtility.ToAbsolute("~/url/"); 
like image 60
Schotime Avatar answered Oct 18 '22 09:10

Schotime


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.

like image 42
Curtis Buys Avatar answered Oct 18 '22 07:10

Curtis Buys