如何在Html.EditorFor中使用占位符属性?

时间:2014-05-04 10:17:18

标签: asp.net html5 razor asp.net-mvc-5 placeholder

我想在Html.EditorFor中使用占位符属性,所以我在第一个答案中就像:Html5 Placeholders with .NET MVC 3 Razor EditorFor extension?

但是在最后一部分,我没有EditorTemplates文件夹,因此我创建了它,当我尝试创建string.cshtml视图时,我无法理解,因为名称"字符串&#34 ;是保留所以我选择了stringg.cshtml,它没有工作!我是否必须在程序的其他位置更改名称?我确实喜欢这个答案......

谢谢!

5 个答案:

答案 0 :(得分:50)

升级到MVC 5.1,您可以在EditorFor中使用HTML属性:

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

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

答案 1 :(得分:9)

 @Html.EditorFor(model => model.members_ssn, new { htmlAttributes = new { @class = "form-control", placeholder = "Your Example Here" } })

答案 2 :(得分:3)

使用TextBoxForTextAreaFor而不是EditorFor时,请仅使用@ Medo答案中的内部键值对,因为该方法直接需要htmlAttributes对象:

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

(我知道这与原始问题相关,但是当我早些时候登陆此页面时,在这里有这个帮助我,寻找如何将占位符文本添加到Html.TextAreaFor的答案!)< / p>

答案 3 :(得分:0)

使用一些jquery,例如:     $(&#34; #FirstName&#34;)。attr(&#34;占位符&#34;,&#34;不要输​​入名称 - 使用搜索按钮&#34;);

答案 4 :(得分:0)

这适用于MVC 5。

就我而言,我想从模型元数据中设置占位符,如下所示:

@Html.EditorFor(model => model.name, new { htmlAttributes = new { @class = "form-control", placeholder = Html.DisplayNameFor(x => x.name) } })