我没有对整数属性应用任何 [Required] 属性验证。但每次我发布表单时,它都会触发验证。最初它在客户端使用 HTML 5 数据属性。我在 Web.config 中将 ClientValidationEnabled 设置为 false。之后它会触发 Required 属性验证。 我创建了一个新项目,但情况相同。试图将 .Net 框架从 4.6 更改为 4.5 但没有成功。还尝试了 VS2015 和 VS 2013 客户端 Razor 代码
@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; }
}
Action 方法
public ActionResult Index()
{
var model = new RegistrationModel();
return View(model);
}
[HttpPost]
public ActionResult Index(RegistrationModel model)
{
if (ModelState.IsValid)
{
}
return View();
}
谢谢
最佳答案
您的模型属性是 typeof int
。 int
必须始终有一个值(它不可为 null),因此无论是否禁用客户端验证,一旦您点击 Controller ,如果您提交一个 ModelState
将无效null
(空字符串)Weight
的值。
如果要允许空值,则必须使属性可为空
public int? Weight { get; set; }
旁注:当您使用 html 帮助程序绑定(bind)到您的模型属性时,您永远不应该尝试设置 value
属性。
关于c# - 仍然需要没有 Required 属性的整数属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33006931/