[ASP.NET Tips and Tricks] Using Prompt Attribute as Placeholder for MVC5

When you build a form in ASP.NET MVC5, you probably use HtmlHelpers, right?

So how do you show a placeholder using the prompt attribute?

31716564800_af2c594490_o

1. Preparing the ViewModel (or Model)

The properties in the ViewModel have the default get set like this

public int DistrictId { get; set; }

You have to add the DisplayAttribute to this Property like this

[Display(Name = "Quận huyện", Prompt = "Gõ để chọn từ danh sách")]
public int DistrictId { get; set; }

DisplayAttribute builds the HTML attributes needed to render on the page when you use HtmlHelpers to create the input tags

The Name property is used for the input’s label, and the Prompt property is used for the input’s placeholder

2. The C# code

Placeholder isn’t a built-in HtmlHelper, so you have to create it yourself

public static class Extensions
{
    public static MvcHtmlString DisplayPlaceHolderFor<TModel, TValue>(this HtmlHelper html,
                                                                      Expression<Func<TModel, TValue>> expression)
    {
        var result = ModelMetadata.FromLambdaExpression(expression, html.ViewData).Watermark;
        return new MvcHtmlString(result);
    }
}

The Expression is the query you pass into this extension

3. The Razor code

//Show the label
@Html.LabelFor(x => x.DistrictId)
//Show the Textbox and the Placeholder
@Html.TextBoxFor(x => x. DistrictId,
                 new {@class = "form-control",
                 placeholder = Html.DisplayPlaceHolderFor(x => x.DistrictId)})

That’s it :D