This post describes how an html5 placeholder can be added to an html input using mvc.

Add the Display attribute to a property in your ViewModel. Set the placeholder text to the Prompt property of this attribute.
MSDN describes the Prompt property as follows:

Gets or sets a value that will be used to set the watermark for prompts in the UI.

This is why I think the Prompt is the right property to use as placeholder.

ViewModel:

[Display(Prompt = "search for cities and countries")]
public string SearchTerm { get; set; }

Create a new EditorTemplate which overwrites the default editor template for properties of type string and save this file on the following location:

Views/Shared/EditorTemplates/String.cshtml

EditorTemplate:

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "text-box single-line", placeholder = ViewData.ModelMetadata.Watermark })

When you want to use placeholders with other types than strings (for example with type int), you should create a custom EditorTemplate for all these types.

The following two tabs change content below.
I'm a software developer from Utrecht. Interested in DDD, continuous delivery, new technologies & frameworks.

Latest posts by Vincent Keizer (see all)