What's the correct way to output HTML attribut

2019-04-07 03:18发布

问题:

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.

回答1:

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


回答2:

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