asp.net-mvc 使用 ASP.NET MVC 辅助方法设置 maxlength 和其他 html 属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/487204/
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
Setting maxlength and other html attributes using ASP.NET MVC helper methods
提问by Kevin Pang
Currently when I want to set html attributes like maxlength and autocomplete, I have to use the following syntax:
目前,当我想设置像 maxlength 和 autocomplete 这样的 html 属性时,我必须使用以下语法:
<%= Html.TextBox("username", ViewData["username"], new { maxlength = 20, autocomplete = "off" }) %>
Is there any way to do this without having to explicitly set the ViewData["username"] portion? In other words, I want to rely on the helper method's automatic loading routine rather than having to explicitly tell it which field to load up from the ViewData.
有没有办法做到这一点而不必显式设置 ViewData["username"] 部分?换句话说,我想依赖辅助方法的自动加载例程,而不是必须明确告诉它从 ViewData 加载哪个字段。
回答by veggerby
Just pass "null" as second parameter:
只需将“null”作为第二个参数传递:
<%= Html.TextBox("username", null, new { maxlength = 20, autocomplete = "off" }) %>
回答by marc.d
yes but you have to use ViewData.Model instead of ViewData.Item()
是的,但你必须使用 ViewData.Model 而不是 ViewData.Item()
the code in your controller should look like this (sry 4 VB.NET code)
控制器中的代码应如下所示(sry 4 VB.NET 代码)
Function Index()
ViewData("Title") = "Home Page"
ViewData("Message") = "Welcome to ASP.NET MVC!"
Dim user As New User
Return View(user)
End Function
now you can do this in the view
现在您可以在视图中执行此操作
<%=Html.TextBox("username", Nothing, New With {.maxlength = 30})%>
note that the user object has a public property username
请注意,用户对象有一个公共属性用户名
hth
第
回答by omoto
I used construction as below:
我使用的构造如下:
<%= Html.TextBox("username", "", new { @maxlength = "20", @autocomplete = "off" }) %>
回答by omoto
For Setting max length of TextBox you can pass "" or null for Second Parameter and set html attributes(maxlength) as third parameter
对于设置 TextBox 的最大长度,您可以为第二个参数传递 "" 或 null 并将 html 属性(maxlength)设置为第三个参数
<%=Html.TextBox("username", "", new { @maxlength = 10 }) %>

