Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantages of razor replace (@href)

In the documentation of ASP.NET MVC says that you should do something like this when have a link in a view

<a href="@href("~/SubPage")">Subpage</a>.

The razor engine replaces @href("~/SubPage")to /Subpage.

What is the advantage of do it this way instead

<a href="/SubPage">Subpage</a>.

In cases like this and in others (like creating a form) why use the razor engine instead of write directly what you want. I think is faster on the server side to print something directly that let the engine to generate it.

like image 637
Ricardo Polo Jaramillo Avatar asked Feb 23 '12 04:02

Ricardo Polo Jaramillo


People also ask

Is Razor pages better than MVC?

From the docs, "Razor Pages can make coding page-focused scenarios easier and more productive than using controllers and views." If your ASP.NET MVC app makes heavy use of views, you may want to consider migrating from actions and views to Razor Pages.

Why Razor is used in MVC?

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 are Razor expressions used for?

Razor Expression Encoding Razor provides expression encoding to avoid malicious code and security risks. In case, if user enters a malicious script as input, razor engine encode the script and render as HTML output.

What is Razor View Engine in MVC?

Razor View Engine is a markup syntax which helps us to write HTML and server-side code in web pages using C# or VB.Net. It is server-side markup language however it is not at all a programming language.


1 Answers

If your application runs in a subfolder, the Razor @href will create the correct link like this:

www.myapp.com/subfolder/SubPage

If you write it by yourself your link will be like this and will not work:

www.myapp.com/SubPage

Thats because ~ will be replaced with your application root by Razor.

like image 191
Marc Avatar answered Oct 06 '22 04:10

Marc