Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html.Raw() in ASP.NET MVC Razor view

@{int count = 0;} @foreach (var item in Model.Resources) {     @(count <= 3 ? Html.Raw("<div class=\"resource-row\">").ToString() : Html.Raw(""))      // some code     @(count <= 3 ? Html.Raw("</div>").ToString() : Html.Raw(""))      @(count++)  } 

This code part does not compile, with the following error

Error   18  Type of conditional expression cannot be determined because there is no implicit conversion between 'string' and 'System.Web.IHtmlString'   d:\Projects\IRC2011_HG\IRC2011\Views\Home\_AllResources.cshtml  21  24  IRC2011 

What I must I do?

like image 756
Artur Keyan Avatar asked Aug 11 '11 14:08

Artur Keyan


People also ask

What is the use of HTML raw () in MVC?

The Html. Raw Helper Method is used to display HTML in Raw format i.e. without encoding in ASP.Net MVC Razor. Please refer the following article for complete information on how to configure Bundles in ASP.Net MVC project.

What is HTML Raw?

Raw(Object) Wraps HTML markup in an HtmlString instance so that it is interpreted as HTML markup. Raw(String) Wraps HTML markup in an HtmlString instance so that it is interpreted as HTML markup.

Why you should never use HTML raw in your razor views?

The bad news is that using this specificity alongside Html. Raw can result in a XSS vulnerability being exploitable since an attacker can craft a special URL containing a malicious JavaScript payload that will be executed by the victim's browser if he or she sends an invalid 2FA confirmation code.

What does HTML raw do C#?

Raw allows you to output text containing html elements to the client, and have them still be rendered as such. Should be used with caution, as it exposes you to cross site scripting vulnerabilities.


2 Answers

Html.Raw() returns IHtmlString, not the ordinary string. So, you cannot write them in opposite sides of : operator. Remove that .ToString() calling

@{int count = 0;} @foreach (var item in Model.Resources) {     @(count <= 3 ? Html.Raw("<div class=\"resource-row\">"): Html.Raw(""))      // some code     @(count <= 3 ? Html.Raw("</div>") : Html.Raw(""))      @(count++)  } 

By the way, returning IHtmlString is the way MVC recognizes html content and does not encode it. Even if it hasn't caused compiler errors, calling ToString() would destroy meaning of Html.Raw()

like image 150
archil Avatar answered Sep 18 '22 22:09

archil


The accepted answer is correct, but I prefer:

@{int count = 0;}  @foreach (var item in Model.Resources)  {      @Html.Raw(count <= 3 ? "<div class=\"resource-row\">" : "")       // some code      @Html.Raw(count <= 3 ? "</div>" : "")       @(count++) }  

I hope this inspires someone, even though I'm late to the party.

like image 23
rfmodulator Avatar answered Sep 22 '22 22:09

rfmodulator