@{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?
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.
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.
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.
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.
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()
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.
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