我有这个:
@Html.TextBoxFor(cModel => cModel.Value, new { id = "txtbLimit", @type = "int" })
我想确保用户输入的内容是一个整数。
我怎样才能做到这一点?
编辑:我不使用模型的值解析此文本框,因此模型验证不是我想要的
编辑2:
型号:
public class StorageConfigurationModel
{
[Required]
public int QueueMonitorConfigurationsID { get; set; }
[Required]
public PathType QueueMonitorConfigTypeName { get; set; }
[Required]
public string Location { get; set; }
[Required]
public UnitType QueueMonitorValueTypeName { get; set; }
[Required]
public ThresholdType Threshold { get; set; }
[Required]
[RegularExpression(@"\d*")]
public int Value { get; set; }
}
public enum PathType
{
Path
}
public enum UnitType
{
MB, GB, TB, Files, Percentage
}
public enum ThresholdType
{
Upper, Lower
}
解析函数:
private static StorageConfigurationModel BindToModel(int id, string pathType, string threshold, string valueType, string location, int limit)
{
return new StorageConfigurationModel
{
QueueMonitorConfigurationsID = id,
QueueMonitorConfigTypeName = (PathType)Enum.Parse(typeof(PathType), pathType),
Location = Convert.ToString(location.Trim()),
Value = Convert.ToInt32(limit),
QueueMonitorValueTypeName = (UnitType)Enum.Parse(typeof(UnitType), valueType),
Threshold = (ThresholdType)Enum.Parse(typeof(ThresholdType), threshold)
};
}
因此,当我将所有数据放入 View 中并单击“添加”时,不会触发任何内容。
通过这个,我调用了调用 modelbinder 的函数:
$.post('@Url.Action("AddUpdateConfigs")',
{id: @Model.QueueMonitorConfigurationsID , pathType: $('#ddlConfigTypeName').val(), threshold:$('#ddlThreshold').val(), valueType:$('#ddlValueTypeName').val(), location: $('#txtbLocation').val(), limit: $('#txtbLimit').val(), config: $('#NewOrUpdate').val() },
function(data){
if (!data.Success){
alert(data.Description);
}
else{
//$('#gridView').load('/Storage/gvConfigurations');
$.get('@Url.Action("gvConfigurations", "Storage")',null,function(data){$('#gridView').html(data);},'html');
}
},'json');
最佳答案
在您的模型上,将此属性添加到Value
的顶部:
[RegularExpression(@"(\d+)")]
并且 MVC 会在返回到 POST 中的 Controller 之前将其设置为无效的服务器端 - 然后您可以轻松正确地处理它。
现在,如果您决定在 JavaScript 中使用它,请使用此方法:
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
然后您可以在 onkeydown
事件中运行它,如下所示:
onkeydown="return isNumber(this.value);"
编辑
要在其中获取错误消息,您应该能够执行以下操作:
[RegularExpression(@"(\d+)", ErrorMessage="Please enter numeric values only.")]
关于c# - 在 MVC(Razor) 中使用 Jquery 验证文本框中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17044186/