Flavio
Flavio

Reputation: 45

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?

Upvotes: 1

Views: 15089

Answers (2)

anlijudavid
anlijudavid

Reputation: 539

It's works:

@{ string text = "any text"; } @Regex.Replace(text, @"<[^>]*>", "").Substring(0, 80);

Upvotes: 1

Kadir
Kadir

Reputation: 3224

@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.

Upvotes: 7

Related Questions