Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add placeholder text from the model into a MVC view?

I have a model:

[DataType(DataType.EmailAddress)]
[DisplayFormat(ConvertEmptyStringToNull = true)]
[Display(Prompt = "Email Address")]
public string Email { get; set; }

I am trying to get the "prompt" to show in the placeholder text of the resulting text box with the following:

@Html.EditorFor(model => model.Email, 
new { htmlAttributes = new { @class = "form-control input-md",
placeholder = @ViewData.ModelMetadata.Watermark } })

When I view the generated HTML I only get "placeholder" in the input tag. According to what I have read ViewData.ModelMetadata.Watermark should work. What is the correct way to get this placeholder text in place?

like image 287
John S Avatar asked Feb 28 '14 21:02

John S


4 Answers

This solved my issue:

@Html.EditorFor(model => model.Email, new { htmlAttributes = 
new { @class = "form-control input-sm", 
placeholder = @Html.DisplayNameFor(m=>m.Email) } })

The code that did it was

placeholder = @Html.DisplayNameFor(m=>m.Email) 
like image 103
John S Avatar answered Nov 17 '22 14:11

John S


A little late, but if someone is still looking for it...

@Html.EditorFor(model => model.Email, 
new { htmlAttributes = new { @class = "form-control input-md",
@placeholder = "Whatever you want as a placeholder" } })

It's perfect and clean!

like image 29
The girl with red hair Avatar answered Nov 17 '22 14:11

The girl with red hair


The correct solution to get the Prompt value instead of the DisplayName in a non-templated control context is the following:

@Html.EditorFor(model => model.Email, 
    new { @class = "form-control input-md",
    placeholder = ModelMetadata.FromLambdaExpression(m => m.Email, ViewData).Watermark
})

This will also - unlike the accepted solution using @Html.DisplayNameFor(m=>m.Email) - not double-escape the watermark text, which depending on the text and the language displayed can be a problem.

like image 7
marapet Avatar answered Nov 17 '22 13:11

marapet


Use TextBoxFor:

@Html.TextBoxFor(m => m.Email, new { @class = "form-control", @placeholder = Html.DisplayNameFor(m => m.Email) })
like image 5
Shalom Dahan Avatar answered Nov 17 '22 13:11

Shalom Dahan