Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are <%: and <%= the same thing as embbed code (expression) blocks

Having just started with MVC 2 I notice that in their starter template they use

<%: Html.ActionLink("Home", "Index", "Home")%> 

and I was sure that in MVC 1 it was

<%= Html.ActionLink("Home", "Index", "Home")%> 

Are they the same thing? If so, why the change from equal sign to colon.

like image 241
Ralph Shillington Avatar asked Apr 20 '10 15:04

Ralph Shillington


People also ask

What are Razor expression used for?

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 @model in Cshtml?

The @model directive allows access to the list of movies that the controller passed to the view by using a Model object that's strongly typed. For example, in the Index.cshtml view, the code loops through the movies with a foreach statement over the strongly typed Model object: CSHTML Copy.

What is Cshtml file?

cshtml extension is a C# HTML file that is used at server side by Razor Markup engine to render the webpage files to user's browser. This server side coding is similar to the standard ASP.NET page enabling dynamic web content creation on the fly as the webpage is written to the browser.

What is a Razor web page?

What is Razor? Razor is a markup syntax that lets you embed server-based code (Visual Basic and C#) into web pages. Server-based code can create dynamic web content on the fly, while a web page is written to the browser.


2 Answers

the colon syntax means you'll be html encoded automatically: http://haacked.com/archive/2009/09/25/html-encoding-code-nuggets.aspx

They couldn't just html encode all the existing <%= blocks, because things that are already properly encoded (which is hopefully most of the projects out there) would look strange.

like image 87
Rob Fonseca-Ensor Avatar answered Sep 27 '22 22:09

Rob Fonseca-Ensor


<%= is used for writing to the output buffer.

<%: is used for writing to the output buffer, after HTML Encoding the content... Unless the IHtmlString Interface has been implemented on the returned object.

Scott Guthrie has an excellent post on this topic: http://weblogs.asp.net/scottgu/archive/2010/04/06/new-lt-gt-syntax-for-html-encoding-output-in-asp-net-4-and-asp-net-mvc-2.aspx

If the output has already been escaped, double encoding can be prevented by implementing the IHtmlString Interface on the returned object. http://msdn.microsoft.com/en-us/library/system.web.ihtmlstring.aspx

like image 39
gahooa Avatar answered Sep 28 '22 00:09

gahooa