Jarnal
Jarnal

Reputation: 2158

Cannot implicitly convert type 'string' to 'System.Web.HtmlString' in C#?

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
});

Upvotes: 28

Views: 40391

Answers (2)

Tauseef
Tauseef

Reputation: 2052

Try using MvcHtmlString.Create(String) Method

If you are using the MVC 5.2 or later.

Upvotes: 3

Sachin Nayak
Sachin Nayak

Reputation: 1051

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

Upvotes: 50

Related Questions