Asp.net mvc 4 ASP.NET MVC post仍然会通过,即使验证应该会阻止它
如果我这样做 视图模型:Asp.net mvc 4 ASP.NET MVC post仍然会通过,即使验证应该会阻止它,asp.net-mvc-4,Asp.net Mvc 4,如果我这样做 视图模型: public class ToleranceInput{ public decimal Tolerance{get;set;} } 在我看来 cshtml.cshtml @model ToleranceInput @using (@Html.BeginForm("AssignTolerances", Tolerances", FormMethod.Post, new {@class="form-horizontal"})) { @H
public class ToleranceInput{
public decimal Tolerance{get;set;}
}
在我看来
cshtml.cshtml
@model ToleranceInput
@using (@Html.BeginForm("AssignTolerances", Tolerances", FormMethod.Post, new {@class="form-horizontal"}))
{
@Html.ValidationSummary()
@Html.Partial("_AssignOrEditTolerances", Model)
<div class="form-actions">
<button type="submit">
<i class="icon-ok icon-white"></i> Save
</button>
</div>
}
标准MVC验证工作正常。当我输入字母(而不是数字)时,它会显示一条红色的错误消息。但是,在viewmodel中,如果我将公差更改为可为空的decimal?
它将无法正常工作。如果我在文本框中键入一个非十进制字符,如'asdf',当我点击save按钮时,我会看到红色验证消息快速闪烁,但随后POST将通过,并且我的控制器中的[HttpPost]assignTolerance
方法将被执行。为什么会这样?有什么想法吗
编辑:我刚刚找到以下链接。看起来字符串被转换为null,解决方法看起来很糟糕:您是否也考虑过在控制器操作中添加检查
[HttpPost]
public ActionResult TestPost(ToleranceInput model)
{
if(!ModelState.IsValid)
{
return View(model);
}
}
然后只需将验证添加到模型中,例如[Required]属性我认为如果希望模型属性为空,应该为其提供一些自定义验证。可能是一个用于十进制值的正则表达式
[RegularExpression(@“^-{0,1}\d+(.\d+{0,1}$)”]
post请求仍然通过自定义验证通过尝试使用[Range(typeof(Decimal),“1”,“9999”]
无法重现此行为。将容差设置为空将显示“字段容差必须是一个数字”。并阻止提交。
[HttpPost]
public ActionResult TestPost(ToleranceInput model)
{
if(!ModelState.IsValid)
{
return View(model);
}
}