asp.net-mvc 如何在 mvc 中添加布尔必需属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26122171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 23:15:21  来源:igfitidea点击:

How to add boolean required attribute in mvc?

asp.net-mvcvalidationmodel

提问by Sonu K

I have one model class like:

我有一个模型类,如:

public class Student
{
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    [Display(Name = "Enrollment Date")]
    public DateTime EnrollmentDate { get; set; }

    [Required]
    [Display(Name = "Is Active")]
    public bool IsActive { get; set; }

    public virtual ICollection<Enrollment> Enrollments { get; set; }
}

Here I have created a Booleanproperty IsActivewith Requiredattribute, but the problem is that my view is not executing the required validation for this property? I want to bind this property with a CheckBoxand check if this CheckBoxis checked and run validation if it is not.

在这里,我已经创建了一个Boolean属性IsActiveRequired属性,但问题是,我的看法是不执行所需的验证此属性?我想用 a 绑定这个属性CheckBox并检查它是否CheckBox被选中,如果没有,则运行验证。

Any solution for this?

有什么解决办法吗?

回答by Sonu K

[Display(Name = "Is Active")]
[Range(typeof(bool), "true", "true", ErrorMessage="The field Is Active must be checked.")]
public bool IsActive { get; set; }

回答by Kris

Thanks for the above solution, which put me in right direction, but for me it didn't work well. I need to add below script to the page that extends jquery validator to get the above solution work. Thought of sharing this if at all someone runs into similar issue.

感谢上述解决方案,它使我朝着正确的方向前进,但对我来说效果不佳。我需要将下面的脚本添加到扩展 jquery 验证器的页面中,以获得上述解决方案的工作。如果有人遇到类似问题,就想分享这个。

<script>
        // extend jquery range validator to work for required checkboxes
        var defaultRangeValidator = $.validator.methods.range;
        $.validator.methods.range = function(value, element, param) {
            if(element.type === 'checkbox') {
                // if it's a checkbox return true if it is checked
                return element.checked;
            } else {
                // otherwise run the default validation function
                return defaultRangeValidator.call(this, value, element, param);
            }
        }
</script>

回答by Odin

Let me add a little to Sonu Kpost

让我添加一点来Sonu K发布

If you use HTML validation on it(<input type="checkbox" required/>) it might end up disrupting your javascript from preventing you to submit an empty required field set from your Model

如果您对其使用 HTML 验证(<input type="checkbox" required/>),它最终可能会破坏您的 javascript,从而阻止您从模型中提交空的必填字段集

Finally, if you don't want the Is Activeto be added to database when doing migration(Code first) just add [NotMapped]

最后,如果您不想Is Active在进行迁移时将其添加到数据库中(代码优先),只需添加[NotMapped]

Full code

完整代码

[NotMapped]
[Display(Name = "Is Active")]
[Range(typeof(bool), "true", "true", ErrorMessage="The field Is Active must be checked.")]
public bool IsActive { get; set; }

because it is set as true by default in MVC despite it will display uncheck on the browser, so the validation might not work as you expect it to, that is why you have to add this javascript code to perfect the validation.

因为它在 MVC 中默认设置为 true 尽管它会在浏览器上显示取消选中,所以验证可能不会像你期望的那样工作,这就是为什么你必须添加这个 javascript 代码来完善验证。

<script>
            // extend jquery range validator to work for required checkboxes
            var defaultRangeValidator = $.validator.methods.range;
            $.validator.methods.range = function(value, element, param) {
                if(element.type === 'checkbox') {
                    // if it's a checkbox return true if it is checked
                    return element.checked;
                } else {
                    // otherwise run the default validation function
                    return defaultRangeValidator.call(this, value, element, param);
                }
            }
        </script>

Enjoy coding

享受编码