Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in #MVC3 is there a way to add the HTML5 placeholder attribute using a DataAnnotations attribute?

given this is my model

public class ValidationModel
{
    #region Properties

    [Display(Prompt = "type a PostCode here")]
    public string PostCode { get; set; }

}

and this is my view

@using (Html.BeginForm())
{
    @Html.LabelFor(m => m.PostCode)
    @Html.TextBoxFor(m => m.PostCode)

}

is there a way to make it render

<input data-val="true" id="PostCode" name="PostCode" placeholder="type a PostCode here" type="text" value="" />

I could not make it work even if from the documentation http://bit.ly/jVpM8X I can clearly see Display Prompt should do the job

like image 940
smnbss Avatar asked Jun 16 '11 16:06

smnbss


2 Answers

@Html.TextBoxFor(m => m.PostCode, 
    new { placeholder = "type a postcode ..." } )
like image 146
Dennis Traub Avatar answered Oct 20 '22 22:10

Dennis Traub


I needed this exact functionality, but I didn't want to go around and change all my EditorFor's to be something different (I have a lot of pages :)).

To achieve this, I simply created a EditorTemplate for String (you can do this for other types should you need it).

Based on my model properties, which I use DisplayName, like so:

[DisplayName("Client Name")]
public string ClientName { get; set; }

The template was simply:

@model string

@Html.TextBoxFor(m => m, new { @placeholder = ViewData.ModelMetadata.DisplayName })

And then my calling code stayed exactly the same:

@Html.EditorFor(m => m.FirstName)

Additionally, you can have this work for non-HTML5 browsers with that exact code. All I did was add a script reference to this great jQuery placeholder plugin and all my placeholders even work in IE6(!!!!).

like image 36
mattytommo Avatar answered Oct 20 '22 20:10

mattytommo