roryok
roryok

Reputation: 9645

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.

Upvotes: 7

Views: 4973

Answers (2)

Nathan Phillips
Nathan Phillips

Reputation: 12425

If you just omit the quotation marks around the value then they will be automatically added for you.

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

Upvotes: 0

Rupo
Rupo

Reputation: 402

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

Upvotes: 8

Related Questions