1

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?

2
  • 3
    string text = Model.lastNoticias.Descricao; ? Commented Sep 1, 2014 at 22:58
  • The Model.lastNoticias.Descricao is an encoded html. I need to decode It and after get the substring. Commented Sep 2, 2014 at 13:02

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

4 Comments

Than you need to remove html tags. Or you need to complete unclosed html tags when you trimmed. Here is the code you need to complete unclosed tags: gist.github.com/kad1r/b92454f76e5b8c017b2e
But the problem is that Model.LasNoticias.Descricao.Length is an encoded html. If I make the solution above, It will be count the html tags too. For example: ` @{ string h = "<spam>teste</spam>"; } @("The h value is: " + h.Substring(0,5)) ` The result is: ` <spam ` What I want is get the decoded text and get the substring values.
basically, what I want is get the decoded text and after test if it > 100 and after get the substring. How can I do it ?
I told you, you have 2 options for that. First you need to remove all html tags from your string (stackoverflow.com/questions/4878452/remove-html-tags-in-string), second one is trimmed and complete unclosed html tags. The code I gave it to you is doing that, even if you trimmed like "<span>asdaj<sp" it's going to close it. You need to choose one of them.
1

It's works:

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

1 Comment

Welcome to StackOverflow! The question you are answering already has an accepted answer. Your answer does not match the community guidelines and probably should be a comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.