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

后端 未结 3 745
醉梦人生
醉梦人生 2020-12-01 07:14
@{int count = 0;}
@foreach (var item in Model.Resources)
{
    @(count <= 3 ? Html.Raw("
").ToString() : Ht
相关标签:
3条回答
  • 2020-12-01 07:45

    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.

    0 讨论(0)
  • 2020-12-01 07:46

    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()

    0 讨论(0)
  • 2020-12-01 07:52

    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.

    0 讨论(0)
提交回复
热议问题