Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在MVC中限制文本框中的字符长度?_C#_.net_Asp.net_Html_Asp.net Mvc - Fatal编程技术网

C# 如何在MVC中限制文本框中的字符长度?

C# 如何在MVC中限制文本框中的字符长度?,c#,.net,asp.net,html,asp.net-mvc,C#,.net,Asp.net,Html,Asp.net Mvc,我想在MVC中将文本框限制为10个字符 <label ID="lbl2" runat="server" Width="20px"></label> <%=Html.TextBox("polNum") %> <label ID="lbl1" runat="server" Width="10px"></label> 我知道您可以在.net中设置“最大长度”属性。如何在MVC中以这种方式生成文本框?您需要设置一些html属性。。

我想在MVC中将文本框限制为10个字符

<label ID="lbl2" runat="server" Width="20px"></label>
<%=Html.TextBox("polNum") %>    
<label ID="lbl1" runat="server" Width="10px"></label>


我知道您可以在.net中设置“最大长度”属性。如何在MVC中以这种方式生成文本框?您需要设置一些html属性。。。 比如:

<%=Html.TextBox("polNum",null, new {maxlength=10}) %>   

祝您好运

使用获取Html属性的:

Html.TextBox( "polNum", "value", new { maxlength="10" } );
使用纯HTML进行此操作:

<%= Html.TextBox("polNum", null, new { @maxlength = "25" }) %>


(之所以使用
null
参数,是因为您不需要默认值…

使用下面的html设置文本框的最大长度 在Html.TextBox中,第二个参数是TextBox的值,所以可以传递“”或null


@Html.EditorFor(model=>model.Telephone,new{htmlAttributes=new{@class=“form control”,@maxlength=“10”})


这里我使用html.Editor(不使用Textboxfor)和数据库中的电话号码字段。我不希望用户键入的电话号码超过10个。

在XHTML中,所有属性的大小写都应为小写,因此maxlength而不是maxlength。亲爱的lemme修复了我造成您的网页爆炸的错误。实际上,您不需要这个重载。您可以跳过null并使用双参数版本。为什么要使用
?那是网络表单。这是MVC,使用一个
标记。这两种方式都有效,所以我不认为这是一个问题,但感谢大家的提醒,我将把它付诸实践……虽然这个代码片段可以解决这个问题,但有助于提高您的响应质量。请记住,您将在将来为读者回答这个问题,而这些人可能不知道您的代码建议的原因。虽然没有造成任何伤害,但此处不需要前面的
@
maxLength,因为它不是像
那样的语言语法
<%=Html.TextBox("polNum", new { maxlength = 10 }) %>
<Textbox id="polNum" maxlength =10 />
new { @class = "MyCssClass", type = "password", value="HurrDurr", 
      textmode="multiline" }
   <%=Html.TextBox("polNum", "", new { maxlength = 10 }) %>