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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1928651/
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-06 21:56:10  来源:igfitidea点击:

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

c#.netasp.nethtmlasp.net-mvc

提问by MrM

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. How do I do that in MVC with a textbox generated this way?

我知道您可以在 .net 中设置 Max Length 属性。我如何在 MVC 中使用以这种方式生成的文本框?

采纳答案by Paul

You need to set some html properties... something like:

您需要设置一些 html 属性...例如:

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

good luck

祝你好运

回答by Canavar

Use the overload of the TextBox methodwhich is getting Html attributes :

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

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

回答by Tomas Aschan

Do it in plain HTML:

在纯 HTML 中执行此操作:

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

(The nullparameter is because you don't want a default value...)

null参数是因为你不想要一个默认值...)

回答by Tomas Aschan

<%=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. It converts the fields of the type into attributes on the, in this case, TextBox control. The resulting HTML looks like

HtmlHelper 使用反射来检查匿名类型。它将类型的字段转换为属性,在本例中为 TextBox 控件。生成的 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" }

回答by Tomas Aschan

Use below html for set max length of TextBox In Html.TextBox second parameter is value for textbox So, you can pass "" or null

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

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

回答by Isaac Zahn

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

@Html.EditorFor(model => model.Telephone, new { htmlAttributes = new { @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. i do not want the user to type more than ten numbers for telephone.

在这里,我使用 html.Editor(不要使用 Textboxfor),并且我使用数据库中的电话号码字段。我不希望用户输入超过十个电话号码。