简体   繁体   中英

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?

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

其作品:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM