7

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.

tereško
  • 58,060
  • 25
  • 98
  • 150
roryok
  • 9,325
  • 17
  • 71
  • 138

2 Answers2

8

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("");
}
Rupo
  • 402
  • 3
  • 8
  • You could use MVCHtmlString although that's only really for MVC2 -> MVC3, iHtmlString provides more future proofing. (HtmlString is .net 4) http://stackoverflow.com/questions/3382860/htmlstring-vs-mvchtmlstring – Paul Zahra Apr 11 '13 at 12:20
  • How do you display the return IHtmlString result from GetStyle in view then? I tried it in MVC 5, it works for literal value, but does not work for the string retrieved from SQL Server, like new HtmlString(stringvaluefromdb); – VincentZHANG Jan 14 '17 at 05:50
0

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 "";
}
Nathan Phillips
  • 11,899
  • 1
  • 31
  • 24