这是我的代码:
型号:
[Required]
[DataType(DataType.Text)]
[Display(Name = "Your company's name")]
public string CompanyName { get; set; }
查看:
@Html.TextBoxFor(m => m.CompanyName, new { @class = "account-input", @placeholder = @Html.DisplayNameFor(m => m.CompanyName), @id = "companyname" })
它将呈现如下:
贵公司的名字
html输出:
<input class="account-input" data-val="true" data-val-required="The Your company's name field is required." id="companyname" name="CompanyName" placeholder="Your company&#39;s name" type="text" value="">
它应该是这样的:
贵公司的名称
为什么文字无法正确呈现?如何防止这种情况?
我已经尝试过了:
@Html.TextBoxFor(m => m.CompanyName, new { @class = "account-input", @placeholder = @Html.Raw(@Html.DisplayNameFor(m => m.CompanyName)), @id = "companyname" })
和这个
@Html.TextBoxFor(m => m.CompanyName, new { @class = "account-input", @placeholder = @Html.Encode(@Html.DisplayNameFor(m => m.CompanyName)), @id = "companyname" })
答案 0 :(得分:42)
我认为这篇文章会对你有所帮助:
我认为还有其他方法可以解决此问题,但这是使用TextBox的一个选项:
@Html.TextBox("CompanyName", HttpUtility.HtmlEncode("Your company's name"))
还有HttpUtility.HtmlDecode
,这可能有助于我们的保存操作。
<强>更新强>
如果你在占位符周围包裹HttpUtility.HtmlDecode
:
@Html.TextBoxFor(m => m.CompanyName, new { @class = "account-input",
@placeholder = HttpUtility.HtmlDecode(Html.DisplayNameFor(x => x.CompanyName).ToHtmlString()),
@id = "companyname" })
占位符返回为: placeholder =“你公司的名字”
答案 1 :(得分:4)
这是一个帮助器displayplaceholder,它将显示占位符而不进行编码。
http://www.davidberube.me/displayplaceholderfor-mvc-placeholder-for-special-characters/
- 编辑 -
public static partial class Extensions
{
public static MvcHtmlString DisplayPlaceHolderFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
var result = html.DisplayNameFor(expression).ToHtmlString();
return new MvcHtmlString(System.Web.HttpUtility.HtmlDecode(result.ToString()));
}
}
答案 2 :(得分:1)
仅仅跳过使用Html.DisplayNameFor会更容易吗?解码和重新编码文本似乎是不必要的。
public static MvcHtmlString DisplayPlaceHolderFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
var resolvedDisplayName = metaData.DisplayName ?? metaData.PropertyName;
if (!string.IsNullOrEmpty(resolvedDisplayName))
return new MvcHtmlString(resolvedDisplayName);
var htmlFieldName = ExpressionHelper.GetExpressionText(expression);
resolvedDisplayName = htmlFieldName.Split('.').Last();
return new MvcHtmlString(resolvedDisplayName);
}