c# - 仍然需要没有 Required 属性的整数属性

标签 c# asp.net-mvc validation asp.net-mvc-5

我没有对整数属性应用任何 [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 intint 必须始终有一个值(它不可为 null),因此无论是否禁用客户端验证,一旦您点击 Controller ,如果您提交一个 ModelState 将无效null(空字符串)Weight 的值。

如果要允许空值,则必须使属性可为空

public int? Weight { get; set; }

旁注:当您使用 html 帮助程序绑定(bind)到您的模型属性时,您永远不应该尝试设置 value 属性。

关于c# - 仍然需要没有 Required 属性的整数属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33006931/

相关文章:

如果使用 <a>,javascript 不会向处理程序提交数据

c# - 从同一台服务器上的 ASP.NET MVC5 Controller 调用经典 ASP

c# - System.Xml.XmlSchemaSet compile() 填充包含的架构 TargetNamespace

c# - 在 EF4 中按 ID 选择通用存储库

c# - 带空格的 WPF/XAML ResourceDictionary

javascript - 无法加载资源: the server responded with a status of 500 (Internal Server Error) while returning image in base64 format from controller

c# - 如何减少 WCF soap 消息大小以节省带宽?

php - "Cannot modify header information - headers already sent by"验证、提交然后重定向时出现问题

java - 不允许的字段验证

java - Thymeleaf @Valid LazyInitializationException