Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the correct way to output HTML attributes / text with quotes in Razor / MVC3?

Lets say I have a function in my model, that generates a style tag based on an int

public string GetStyle(int? size){
    if(size > 99)
        return "style=\"margin: 20px;\"";
    else
        return "";
}

If I render this out using

<li @GetStyle(123)>123</li>

It outputs this:

<li style=""margin:20px;"">123</li>

(Note the double double-quotes). If I change the escaped double quotes in the function to single quotes, it outputs this:

<li style="'margin:20px;'">123</li>

Neither is correct, and I'm forced to either output an empty style tag if no style is required.

like image 428
roryok Avatar asked Mar 12 '12 11:03

roryok


1 Answers

Change your method so it returns a IHtmlString instead, something like this:

public IHtmlString GetStyle(int? size)
{
    if(size > 99)
        return new HtmlString("style=\"margin: 20px;\"");
    else
        return new HtmlString("");
}
like image 57
Rupo Avatar answered Oct 22 '22 05:10

Rupo