ASP MVC编码剃刀在输入占位符的特殊字符(ASP MVC Razor encode specia

2019-07-21 02:03发布

这是我的代码:

模型:

[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&amp;#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" })

Answer 1:

我觉得这篇文章将帮助你:

HTML编码解码C#MVC4

我认为有其他的方式来获得这种行为,但是这是使用文本框的一个选项:

@Html.TextBox("CompanyName", HttpUtility.HtmlEncode("Your company&#39;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" })

占位符的返回:占位符=“您的公司名称”



Answer 2:

这里有一个帮手displayplaceholderfor将出现占位符不进行编码。

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()));
   }
}


Answer 3:

那岂不是更容易地就跳过使用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);
}


文章来源: ASP MVC Razor encode special characters in input placeholder