MVC4 FoolProof数据注释-如何检查该字段不等于零? [英] MVC4 FoolProof Data Annotations - How to check that field does not equal to zero?

查看:46
本文介绍了MVC4 FoolProof数据注释-如何检查该字段不等于零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用MVC Foolproof库来验证我的模型并分别显示错误消息.但是,当我使用万无一失"验证时,即使单击常规按钮也无法显示提交"按钮.

I am trying to use MVC Foolproof library to validate my model and show error message respectively. However when I use Foolproof validation, on clicking the submit button even the regular validation is not showing.

我的要求是我有一个数字文本框,并且不应为null或零.该文本框值是根据从上一个下拉列表中选择的值计算得出的.

My requirement is that I have a numeric textbox and it should not be null or zero.The textbox value is calculated based on the value selected from the previous dropdownlist.

下面是带有数据注释的模型中两个字段的代码,

Below is the code for both fields in the model with data annotation,

using Foolproof;

  [Required(ErrorMessage = "Fee is not given", AllowEmptyStrings = false)]
    [NotEqualTo("0",ErrorMessage="Duration cannot be zero")]
    public Nullable<int> Duration { get; set; }

HTML文本框

 @Html.TextBoxFor(m => m.MultiCourse.Duration,
        new { @class = "form-control", @placeholder = "Course Duration", @id = "txtCourseDuration" })
            @Html.ValidationMessageFor(m => m.MultiCourse.Duration)

捆绑配置类

 bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/plugins/jQueryVal/jquery.unobtrusive*",
                    "~/plugins/jQueryVal/jquery.validate*",
                    "~/plugins/jQueryVal/mvcfoolproof.unobtrusive*"));

推荐答案

万无一失的[NotEqualTo]属性将属性的值与另一个属性的值进行比较.在您的情况下,这将引发异常,因为您的模型不(也不能)包含名为0的属性.

The foolproof [NotEqualTo] attribute compares the value of the property with the value of another property. In your case this would throw an exception because you model does not (and cant) contain a property named 0.

如果仅允许使用正值,则可以使用[Range]属性

If only positive values are allowed, then you could use a [Range] attribute

[Range(1, int.MaxValue, ErrorMessage = "Duration must be greater than zero")]
public Nullable<int> Duration { get; set; }

或者,如果允许使用负值,则可以在视图模型中包含一个属性(例如)int InvalidDuration并使用

Alternatively if negative values were allowed, you could include a property in your view model (say) int InvalidDuration and use

[NotEqualTo("InvalidDuration", ErrorMessage="Duration cannot be zero")]
public Nullable<int> Duration { get; set; }

并在视图中包含隐藏的输入

and include a hidden input in the view

@Html.HiddenFor(m => m.InvalidDuration)

这篇关于MVC4 FoolProof数据注释-如何检查该字段不等于零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆