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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23455043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 01:42:23  来源:igfitidea点击:

How can I use placeholder attribute with Html.EditorFor?

asp.nethtmlrazorasp.net-mvc-5placeholder

提问by caj

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?

我想在 Html.EditorFor 中使用 placeholder 属性,所以我就像在第一个答案中一样: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...

但在最后一部分,我没有 EditorTemplates 文件夹,所以我创建了它,当我尝试创建 string.cshtml 视图时我不能,因为名称“string”被保留,所以我选择 stringg.cshtml 而不是没用!我是否必须在程序中的其他地方更改名称?我确实很喜欢这个答案......

Thank you!

谢谢!

回答by Medo

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

升级到 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

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

回答by Jay

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

回答by César León

This works for MVC 5.

这适用于 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) } })

回答by Jon Schneider

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

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

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

(我意识到这与原始问题无关,但是当我早些时候登陆此页面时,将其放在此处会对我有所帮助,寻找如何将占位符文本添加到Html.TextAreaFor!)

回答by Antony D

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

使用一些 jquery,例如: $("#FirstName").attr("placeholder", "Do not type name - use Search button");