【发布时间】:2016-01-05 13:15:56
【问题描述】:
我没有对整数属性应用任何 [必需] 属性验证。但每次我发布表单时,它都会触发验证。最初它在客户端使用 HTML 5 数据属性。我在 Web.config 中将 ClientValidationEnabled 设置为 false。之后,它会触发必需的属性验证。 我创建了一个新项目,但情况相同。试图将 .Net 框架从 4.6 更改为 4.5,但没有成功。还尝试过 VS2015 和 VS 2013 客户端剃须刀代码
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.LabelFor(model => model.Weight)
@Html.TextBoxFor(model => model.Weight, new { @class = "form-control", @placeholder = "Weight", Value = "" })
@Html.ValidationMessageFor(model => model.Weight, "", new { @class = "text-danger" })
<input type="submit" class="btn btn-default" value="Save" />
}
型号:
public class RegistrationModel
{
public int Weight { get; set; }
}
动作方法
public ActionResult Index()
{
var model = new RegistrationModel();
return View(model);
}
[HttpPost]
public ActionResult Index(RegistrationModel model)
{
if (ModelState.IsValid)
{
}
return View();
}
谢谢
【问题讨论】:
-
尽可能显示
model代码以及模型和视图中的所有其他属性? -
您不需要将
[Required]属性应用于int的属性 - 默认情况下需要它(它必须有一个值)。如果您为Weight发布包null(空字符串)值,那么您将始终收到验证错误。如果您希望它可以为空,则需要将其设为public int? Weight { get; set; } -
并且在使用 html 帮助程序时永远不要尝试设置
value属性(就像您使用new { Value = "" }所做的那样) -
显示您的模型代码和操作方法
-
@Hiba 我刚刚编辑了我的问题。但斯蒂芬·穆克的评论是正确的。这是整数类型属性的默认行为。
标签: c# asp.net-mvc validation asp.net-mvc-5