简体   繁体   English

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

[英]How do I limit the length of characters in a textbox in MVC?

I would like to limit a textbox to 10 characters in MVC. 我想在MVC中将文本框限制为10个字符。

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

I know you can set the Max Length property in .net. 我知道您可以在.net中设置“最大长度”属性。 How do I do that in MVC with a textbox generated this way? 我如何在MVC中使用这种方式生成的文本框来做到这一点?

You need to set some html properties... something like: 您需要设置一些html属性...类似:

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

good luck 祝好运

Do it in plain HTML: 使用纯HTML格式:

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

(The null parameter is because you don't want a default value...) null参数是因为您不需要默认值...)

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

http://msdn.microsoft.com/en-us/library/dd492984.aspx http://msdn.microsoft.com/en-us/library/dd492984.aspx

HtmlHelper uses reflection to examine the anonymous type. HtmlHelper使用反射来检查匿名类型。 It converts the fields of the type into attributes on the, in this case, TextBox control. 它将类型的字段转换为TextBox控件上的属性。 The resulting HTML looks like 生成的HTML看起来像

<Textbox id="polNum" maxlength =10 />

You can use the anonymous type to add other relevant attributes, such as 您可以使用匿名类型添加其他相关属性,例如

new { @class = "MyCssClass", type = "password", value="HurrDurr", 
      textmode="multiline" }

使用获取Html属性的TextBox方法重载

Html.TextBox( "polNum", "value", new { maxlength="10" } );

使用以下html设置TextBox的最大长度,在Html.TextBox中,第二个参数是textbox的值,因此,您可以传递“”或null

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

@Html.EditorFor(model => model.Telephone, new { htmlAttributes = new { @class = "form-control", @maxlength = "10" } }) @ Html.EditorFor(模型=>模型。电话,新{htmlAttributes =新{@class =“ form-control”,@maxlength =“ 10”}})

Here i use html.Editor (do not use Textboxfor) For and i am use the Telephone number field in my database. 在这里,我使用html.Editor(不使用Textboxfor),并且我使用数据库中的电话号码字段。 i do not want the user to type more than ten numbers for telephone. 我不希望用户键入十个以上的电话号码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM