DisplayPlaceHolderFor – MVC Placeholder for special characters

The razor view engine display encoded chars for special caracters. The reason for that is the HtmlHelper extension method DisplayNameFor add a HttpUtility.HtmlEncode(resolvedDisplayName)) in it’s method call. The encoded characters are not supported by html 5 place holders and so they are displayed as is.

change_password_placeholderEncoding

See the source code references here :

https://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/Html/DisplayNameExtensions.cs

 

One simple work around is to use the following

 @Html.PasswordFor(m => m.ConfirmNewPassword, new { @class = “form-control”, placeholder = @System.Web.HttpUtility.HtmlDecode(Html.DisplayNameFor(m=>m.ConfirmNewPassword)) })

This is not very fancy, and you need to rewrite the html decode for every placeholder in your app.

 

So here is an elegant way to work around this.

 

1. Add the following class in your web app

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

using System.Web.Mvc.Html;

namespace WebApp.Extensions
{
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. Add the extension namespace to your mvc views (web.config)

<system.web.webPages.razor>
<host factoryType=”System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35″ />
<pages pageBaseType=”System.Web.Mvc.WebViewPage”>
<namespaces>
<add namespace=”WebApp.Extensions” />

</namespaces>
</pages>
</system.web.webPages.razor>

3. From any views in your app you can now display unencoded text for place holder using  @Html.DisplayPlaceHolderFor(m=>m.ConfirmNewPassword)

@Html.PasswordFor(m => m.ConfirmNewPassword, new { @class = “form-control”, placeholder = @Html.DisplayPlaceHolderFor(m=>m.ConfirmNewPassword)})

 

 

 

1 Comment

  1. Merci! Je vais utiliser l’extension dans mon projet.

    Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

Share This