How can I use placeholder attribute with Html.EditorFor?
Asked Answered
P

5

43

I want to use the placeholder attribute in the Html.EditorFor so I did just like in the first answer: Html5 Placeholders with .NET MVC 3 Razor EditorFor extension?

But in the final part, I don't have the EditorTemplates folder so I created it and when I tried to create the string.cshtml view I couldn't because the name "string" is reserved so I chose stringg.cshtml instead and it didn't work! Do I have to change the name elsewhere in my program? I did exactly like the answer...

Thank you!

Posner answered 4/5, 2014 at 10:17 Comment(0)
H
65

Upgrade to MVC 5.1 and you can use HTML attributes in EditorFor:

@Html.EditorFor(m => m.variable, new { htmlAttributes = new { placeholder = "Your Placeholder Text" } })

http://www.asp.net/mvc/overview/releases/mvc51-release-notes

Hutchison answered 5/5, 2014 at 17:45 Comment(4)
+1 - Thank you for that link. I would say this is your best option if you're willing to upgrade to 5.1. Works great.Biblio
Why did you have to use @ before the placeholder attribute?Catnap
I'm not sure why, but that's how it's done. When you enumerate htmlAttributes you need to use @ for them to be recognized. (@class, @id ...)Hutchison
@Catnap @Hutchison @ is not necessary in this case. @ is used only if variable name is the same as any of the C# keywords, i.e. @class.Knowing
K
18
 @Html.EditorFor(model => model.members_ssn, new { htmlAttributes = new { @class = "form-control", placeholder = "Your Example Here" } })
Kitchenette answered 25/8, 2016 at 14:58 Comment(1)
Do you mind taking a few minutes and explain what your code is doing?Becerra
A
7

This works for MVC 5.

In my case i was looking to set the placeholder from the model metadata, like this:

@Html.EditorFor(model => model.name, new { htmlAttributes = new { @class = "form-control", placeholder = Html.DisplayNameFor(x => x.name) } })
Asymptote answered 26/6, 2018 at 17:14 Comment(0)
I
4

When using TextBoxFor or TextAreaFor rather than EditorFor, use only the inner key-value pair from @Medo's answer, since the method directly expects an htmlAttributes object:

@Html.TextBoxFor(m => m.variable, new { placeholder = "Your Placeholder Text" })

(I realize this is tangential to the original question, but having this here would have helped me when I landed on this page earlier, looking for an answer to how to add placeholder text to an Html.TextAreaFor!)

If answered 23/8, 2016 at 18:3 Comment(0)
R
0

Use some jquery, eg: $("#FirstName").attr("placeholder", "Do not type name - use Search button");

Recipience answered 26/7, 2017 at 6:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.