I am just wondering if I have to worry about encoding the values that get output when I use HTML helpers like Html.DropDownList()
.
我只是想知道在使用HTML帮助程序(如Html.DropDownList())时是否必须担心编码获取输出的值。
If so, how do I encode them? It's easy to do if I were building the drop down manually -- just wrap each value with "Html.Encode()
". However, I don't know how to do this when using HTML helpers.
如果是这样,我该如何编码呢?如果我手动构建下拉菜单,那么很容易做到 - 只需用“Html.Encode()”包装每个值。但是,在使用HTML帮助程序时,我不知道如何执行此操作。
2 个解决方案
#1
It looks like the values are encoded automatically, so there's no reason to do it yourself. Here's a snippet from the actual ASP.NET MVC 1.0 source code that you can download from codeplex (in SelectExtensions.cs):
看起来值是自动编码的,所以没有理由自己编写。以下是您可以从codeplex(在SelectExtensions.cs中)下载的实际ASP.NET MVC 1.0源代码的片段:
private static string ListItemToOption(SelectListItem item) {
TagBuilder builder = new TagBuilder("option") {
InnerHtml = HttpUtility.HtmlEncode(item.Text)
};
if (item.Value != null) {
builder.Attributes["value"] = item.Value;
}
if (item.Selected) {
builder.Attributes["selected"] = "selected";
}
return builder.ToString(TagRenderMode.Normal);
}
#2
They do.
If you want to do it yourself it's Html.Encode()
and Html.AttributeEncode()
depending on where in the HTML you're encoding.
如果你想自己做,那就是Html.Encode()和Html.AttributeEncode()取决于你编码的HTML中的位置。
#1
It looks like the values are encoded automatically, so there's no reason to do it yourself. Here's a snippet from the actual ASP.NET MVC 1.0 source code that you can download from codeplex (in SelectExtensions.cs):
看起来值是自动编码的,所以没有理由自己编写。以下是您可以从codeplex(在SelectExtensions.cs中)下载的实际ASP.NET MVC 1.0源代码的片段:
private static string ListItemToOption(SelectListItem item) {
TagBuilder builder = new TagBuilder("option") {
InnerHtml = HttpUtility.HtmlEncode(item.Text)
};
if (item.Value != null) {
builder.Attributes["value"] = item.Value;
}
if (item.Selected) {
builder.Attributes["selected"] = "selected";
}
return builder.ToString(TagRenderMode.Normal);
}
#2
They do.
If you want to do it yourself it's Html.Encode()
and Html.AttributeEncode()
depending on where in the HTML you're encoding.
如果你想自己做,那就是Html.Encode()和Html.AttributeEncode()取决于你编码的HTML中的位置。