[asp.net-mvc] 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?

This question is related to asp.net-mvc razor

The answer is


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.


You shouldn't be calling .ToString().

As the error message clearly states, you're writing a conditional in which one half is an IHtmlString and the other half is a string.
That doesn't make sense, since the compiler doesn't know what type the entire expression should be.


There is never a reason to call Html.Raw(...).ToString().
Html.Raw returns an HtmlString instance that wraps the original string.
The Razor page output knows not to escape HtmlString instances.

However, calling HtmlString.ToString() just returns the original string value again; it doesn't accomplish anything.