required attribute not working in asp.net mvc

前端 未结 6 1560
离开以前
离开以前 2020-12-03 19:53

I have a simple strongly-typed view.

@model GoldForGold.Models.LogonModel
@{
    ViewBag.Title = \"Logins\";
    Layout = \"~/Views/Shared/_Layout.cshtml\";         


        
6条回答
  •  无人及你
    2020-12-03 20:41

    One other thing to be wary of with [Required] is when using it on an integer field, not just when storing a numeric value, but also, say, when storing the id of the selected value of a dropdown/select list.

    [Required] won't work in that situation because an integer property can never be null and so always has a default value of zero. [Required] is checking that the property has a value, and zero is considered a value, so the check will pass.

    In that case either declare the property as a nullable integer instead:

        [Required]
        public int? LanguageId { get; set; } // note the int is now nullable
    

    or alternatively use the Range attribute to stop zero being an acceptable value:

        [Range(1, int.MaxValue)]
        public int LanguageId { get; set; }
    

提交回复
热议问题