Flavio Flavio - 2 months ago 14
C# Question

Convert @Html.Raw to string in ASP.NET MVC 4 Razor

What I want is to convert the output IHtmlString to String.

I have this code:

string text = @Html.Raw(Model.lastNoticias.Descricao);


This code return the error:

Cannot implicitly convert type System.Web.IHtmlString to string.

The full code:

@{
string text = @Html.Raw(Model.lastNoticias.Descricao);
}
@if (text.Length > 100)
{
@(text.Substring(0, 100) + "... ");
}


How can I do it?

Answer
@if (Model.lastNoticias.Descricao.Length > 100)
{
    @Html.Raw(Model.lastNoticias.Descricao.Substring(0, 100) + " ...");
}
else
{
    @Html.Raw(Model.lastNoticias.Descricao);
}

Also note that you don't want to trimmed an escaped string. You never know what you are trimming. The solution here does it correctly.