简体   繁体   English

试图限制ASP.NET MVC中int数据类型的大小限制

[英]Trying to restrict size limit for int datatype in ASP.NET MVC

I am trying to fix the size range of int datatype textbox to only two digits. 我正在尝试将int数据类型文本框的大小范围固定为仅两位数。 But I'm not able to so. 但是我不能。 Any idea would be appreciated. 任何想法将不胜感激。

CoilEntry.cs is the model class where OUT_P_NO is the int property I would like to restrict to a maximum of two digits. CoilEntry.cs是模型类,其中OUT_P_NO是我想限制为最多两位数的int属性。

CoilEntry.cshtml shows its html part. CoilEntry.cshtml显示其html部分。

Coilentry.cs (model class) Coilentry.cs (模型类)

public class CoilEntry
{
    [Range(0,99, ErrorMessage="Please use values between 0 to 30")]
    public int OUT_P_NO { get; set; }
}

CoilEntry.cshtml CoilEntry.cshtml

@using (Html.BeginForm("CoilEntry", "Home", FormMethod.Post))
{
        <table border="0" cellpadding="0" cellspacing="0">
            <tr>
                <th colspan="3">
                    Coil Entry Detail
                </th>
            </tr>
            <tr>
                <td>
                    OUT PART NO
                </td>
                <td>
                   @Html.TextBoxFor(m=>m.OUT_P_NO,new {@type="number",@maxlength=2,@size=2})
                  </td>
</table>
} 

The expected result would be that the textbox would only allow values from 0 to 99. 预期结果将是该文本框仅允许使用0到99之间的值。

Currently, the textbox allows only numeric values, but value beyond two digits can be entered. 当前,文本框仅允许数字值,但可以输入超过两位数字的值。

You need change to @type = "text" and add event for keypress 您需要更改为@type =“ text”并为keypress添加事件

Add this to script section of page in cshtml file. 将此添加到cshtml文件中页面的脚本部分。 #OUT_P_NO is id generate when use @Html.TextBoxFor(m => m.OUT_P_NO 使用@Html.TextBoxFor(m => m.OUT_P_NO #OUT_P_NO是ID生成

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
    $('#OUT_P_NO').keypress(function(evt) {
            var charCode = (evt.which) ? evt.which : event.keyCode;
            if (charCode > 31 && (charCode < 48 || charCode > 57))
                return false;
            return true;
    });
</script>

Change type="number" to "text" 将type =“ number”更改为“ text”

@Html.TextBoxFor(m => m.OUT_P_NO, new { @type = "text", @maxlength = 2, @size = 2 })

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

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