在Razor / MVC3中使用引号输出HTML属性/文本的正确方法是什么?

时间:2022-09-09 22:29:23

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

假设我的模型中有一个函数,它生成一个基于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.

两者都不正确,如果不需要样式,我将*输出空样式标记。

2 个解决方案

#1


6  

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

更改您的方法,以便它返回一个IHtmlString,如下所示:

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

#2


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

#1


6  

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

更改您的方法,以便它返回一个IHtmlString,如下所示:

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

#2


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