28

I get the error "Cannot implicitly convert type 'string' to 'System.Web.HtmlString' when I attempt to assign a value to a variable of type htmlstring, the value is being read from an xml file (code snippet below)

The convert method does not have a built in conversion from string to htmlstring. There is a method ToHtmlString but not sure how to use it in this situation as it is not available with a string object. Your suggestions please.

public class Xclass
{
    public HtmlString content { get; set; }
    public string id { get; set; }    
}

Xclass x = (from c in xdoc.Descendants("div") select new Xclass()
{
    content = c.Value, //c.value is the html content of div, content is a property of   type HtmlString 
    id = c.id
});
1
  • You have a string. It wants a HtmlString so, how can you get from one to the other? And what issues may there be? (Hint: it won't be encoded again, which could be...) Commented Jan 5, 2012 at 5:31

2 Answers 2

50

can you not do content =new HtmlString(c.Value); ?

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

4 Comments

Thanks Sachin for your super quick response, that did indeed fix that error!
Also you can do that in short like this: @"" + c.Value
[MvcHtmlString.Create(String)]
3

Try using MvcHtmlString.Create(String) Method

If you are using the MVC 5.2 or later.

Comments

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.