How can I use placeholder attribute with Html.Edit

2019-03-22 20:30发布

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!

5条回答
叼着烟拽天下
2楼-- · 2019-03-22 20:59

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!)

查看更多
Root(大扎)
3楼-- · 2019-03-22 21:04

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) } })
查看更多
成全新的幸福
4楼-- · 2019-03-22 21:08

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

查看更多
看我几分像从前
5楼-- · 2019-03-22 21:09

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

查看更多
狗以群分
6楼-- · 2019-03-22 21:20
 @Html.EditorFor(model => model.members_ssn, new { htmlAttributes = new { @class = "form-control", placeholder = "Your Example Here" } })
查看更多
登录 后发表回答