在ASP.NET MVC应用程序中,我使用TagBuilder
创建只读输入字段。
public class DisplayTextFieldBuilder<TModel, TProperty>
{
private HtmlHelper<TModel> _helper;
private Expression<Func<TModel, TProperty>> _expression;
public DisplayTextFieldBuilder(HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
{
_helper = helper;
_expression = expression;
}
public override string ToString()
{
var id = _helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(_expression));
var name = _helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(_expression));
var value = HttpUtility.HtmlEncode(_helper.DisplayFor(_expression).ToString());
TagBuilder builder = new TagBuilder("input");
builder.MergeAttribute("value", value);
builder.MergeAttribute("id", id);
builder.MergeAttribute("name", name);
builder.MergeAttribute("readonly", "readonly");
var html = builder.ToString(TagRenderMode.SelfClosing);
return html;
}
但是某些字符串无法正确呈现。例如,假设模型属性值为 Foe`s BBQ (注意它有撇号)
然后
HttpUtility.HtmlEncode(_helper.DisplayFor(_expression).ToString())
将此值呈现为Foe&#39;s, BBQ
如果我删除html编码,那么
_helper.DisplayFor(_expression).ToString()
将此值呈现为Foe's, BBQ
我缺少什么?