MVC5 Display Placeholder using Prompt attribute

While I was building a simple User Interface using ASP.NET MVC5 I came across this issue of displaying placeholder values using view model display prompt attribute is not working strait away. I googled to find solutions was not fruitful. Most of them were suggesting to use the inline text rather taking it from the view model as follows.

How to user view model prompt attribute as watermark

<div class="form-group">
    @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control", @placeholder = "Email address here.." } }) 
        @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
     </div>
</div>

In the view you are setting up display attributes for each property mostly with a combination of name and prompt as follows;

view model representation of the prompt attribute

Using @Html.DisplayNameFor() helper you can get the name attribute quickly. But there is no strait forward method to get the prompt value.

Solution to get watermark or the placeholder value using the view model prompt attribute is as follows;

In the view you need to use following code to get the prompt value from the view model

 <div class="form-group">
     @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
     <div class="col-md-10">
         @Html.EditorFor(model => model.Email, new { 
             htmlAttributes = new { 
                @class = "form-control", 
                @placeholder = ModelMetadata.FromLambdaExpression(x => x.Email, ViewData).Watermark 
             } 
          }) 
         @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
     </div>
 </div>

You can use ModelMetadata.FromLambdaExpression() method to extract the view model prompt attribute value.

Hope it helps

Leave a Comment

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

Time limit is exhausted. Please reload the CAPTCHA.