【问题标题】:Bold Text in Html.FormatValue using Razor使用 Razor 的 Html.FormatValue 中的粗体文本
【发布时间】:2014-06-16 07:13:37
【问题描述】:
我想得到以下结果。用户名必须是粗体:
Blabla 用户名 Bla.
我在资源文件中有格式:
布拉布拉{0}布拉。
在视图中我执行以下操作:
@Html.FormatValue(User.Identity.Name, Resources.MyFormatString)
如何使用户名加粗并使用 Html.FormatValue?或者有其他方法可以实现吗?
【问题讨论】:
标签:
c#
asp.net-mvc-4
razor
resource-files
【解决方案1】:
您可以简单地更改您的资源以包含粗体标签、强标签或样式。
点赞"Blabla <b>{0}</b> Bla.".
[编辑]
确实,检查了 Html.FormatValue 的转义功能,没有看到,但显然它确实有:)
在这种情况下,使用@Html.Raw 和string.Format 将起作用。
@Html.Raw(string.Format(Resources.MyFormatString, "SomeName"))
(在 MVC 5 中测试,但 @Html.Raw 在 4 中也可用)
还有一个小提示:将 HTML 存储在资源中可能不是最好的主意,混合 UI 和内容。
[/编辑]
【解决方案2】:
我想通过包含 html 标记来解决您的示例,确保资源中的 html 字符安全,并安全地包含用户输入或 html 标记。我对你的例子的解决方案是
@(Resources.MyFormatString.FormatWithHtml(
"<b>" + HttpUtility.HtmlEncode(User.Identity.Name) + "</b>"))
使用我的函数FormatWithHtml
/// Encodes to MvcHtmlString and includes HTML tags or already encoded strings, placeholder is the '|' character
public static MvcHtmlString FormatWithHtml (this string format, params string[] htmlIncludes)
{
var result = new StringBuilder();
int i = -1;
foreach(string part in format.Split('|')) {
result.Append(HttpUtility.HtmlEncode(part));
if (++i < htmlIncludes.Length)
result.Append(htmlIncludes[i]);
}
return new MvcHtmlString(result.ToString());
}
还有一个例子,这个
@("Resource is safe to html characters <&> and will include |format tags| or any | user input."
.FormatWithHtml("<b>", "</b>", "<b id='FromUser'>" +HttpUtility.HtmlEncode("<a href='crack.me'>click</a>") +"</b>"))
将写入您的剃须刀页面
资源对 html 字符 是安全的,并且将包含 格式标签 或任何 click 用户输入.