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

43

我想在Html.EditorFor中使用placeholder属性,因此我像第一个答案中一样操作:Html5 Placeholders with .NET MVC 3 Razor EditorFor extension?

但在最后一部分中,我没有EditorTemplates文件夹,所以我创建了它,并尝试创建string.cshtml视图,但无法创建,因为“string”名称被保留,所以我选择了stringg.cshtml,但它没有起作用! 我是否需要在程序的其他地方更改名称?我按照答案中的操作进行了操作...

谢谢!

5个回答

65

+1 - 谢谢你提供的链接。如果你愿意升级到5.1,我会说这是你最好的选择。效果非常好。 - Termato
1
为什么在“占位符”属性之前必须使用@ - Yoda
我不确定为什么,但这就是做法。当你枚举htmlAttributes时,需要在它们前面加上@才能被识别。(@class,@id ...) - Medo
12
@Yoda @Medo 在这种情况下不需要使用 @。只有在变量名与任何C#关键字相同时才使用 @,例如 @class - romanoza

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

5
你介意花几分钟时间解释一下你的代码在做什么吗? - DᴀʀᴛʜVᴀᴅᴇʀ

7

这适用于MVC 5。

在我的情况下,我想从模型元数据中设置占位符,像这样:

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

4

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

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

我知道这与原始问题无关,但如果早些时候我着陆在这个页面上寻找如何向Html.TextAreaFor添加占位符文本的答案,这将有所帮助!


0
дҪҝз”ЁдёҖдәӣ jQueryпјҢдҫӢеҰӮпјҡ $("#FirstName").attr("placeholder", "дёҚиҰҒиҫ“е…Ҙ姓еҗҚ - дҪҝз”ЁжҗңзҙўжҢүй’®");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接