ASP MVC Razor encode special characters in input placeholder

▼魔方 西西 提交于 2019-11-27 14:38:01
Luke Duddridge

I think this post will help you:

HTML encode decode c# MVC4

I think there are other ways to get this behaviour, but this is one option of using the TextBox:

@Html.TextBox("CompanyName", HttpUtility.HtmlEncode("Your company's name"))

There is also HttpUtility.HtmlDecode, which might help with our save action.

update

if you wrap HttpUtility.HtmlDecode around your place holder:

@Html.TextBoxFor(m => m.CompanyName, new { @class = "account-input", 
@placeholder = HttpUtility.HtmlDecode(Html.DisplayNameFor(x => x.CompanyName).ToHtmlString()), 
@id = "companyname" })

the placeholder returns as: placeholder="Your company's name"

David Bérubé

Here's an helper displayplaceholderfor that will present placeholder without encoding.

http://www.davidberube.me/displayplaceholderfor-mvc-placeholder-for-special-characters/

-- EDIT --

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

Wouldn't it be easier to just skip using Html.DisplayNameFor? Decoding and re-encoding the text seems unneeded.

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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!