如何在MVC验证中比较两个值?

时间:2015-09-07 06:55:32

标签: c# asp.net-mvc properties

我正在创建一个应用程序,我有年龄范围,体重范围,身高范围等。所以在这些领域我每个都使用两个文本框。例如,对于年龄范围,我使用Age From和Age To这两个文本框,依此类推其他属性。但是我试图找到一个解决方案来比较Age From和Age To来检查Age To是否比Age From更大,反之亦然。为了达到这个目的,我从NUGET下载了Foolproof,并且这样做:

    [GreaterThan("WeightFrom",ErrorMessage="Please verify the Weight Range")]
    public string WeightTo { get; set; }

但是这个Validator会检查该字段是否为必填字段。因为用户可能根本不填写此标准,但如果他们填写,那么我需要检查输入以确保Weight To大于Weight From值。所以,请告诉我如何实现这一目标。还有其他方法吗?感谢。

2 个答案:

答案 0 :(得分:0)

如果您使用“WeightTo”属性数据类型作为int,则可以将数据注释用作[Range(0,100)]到权重范围。

答案 1 :(得分:0)

在你的帖子方法中,在那里进行检查,并为WeightTo和WeightFrom使用可空的整数。我在这里为你创建了一个DotNetFiddle https://dotnetfiddle.net/ci0V2I

控制器

    [HttpGet]
    public ActionResult Index()
    {
        return View(new SampleModel());
    }


    [HttpPost]
    public ActionResult Index(SampleModel model)
    {       
        if(model.WeightFrom.HasValue && model.WeightTo.HasValue)
        {
            if(model.WeightFrom.Value < model.WeightTo.Value)
            {
                ModelState.AddModelError("", "Weight from most be smaller than Weight to. Please fix this error."); 
            }
        }

        if(!ModelState.IsValid)
        {
            return View(model); 
        }

        return View(new SampleModel());
    }

模型

using System;
using System.ComponentModel.DataAnnotations;

namespace HelloWorldMvcApp
{
    public class SampleModel
    {
        [Display(Name = "Weight Form")]
        public int? WeightFrom { get; set; }

        [Display(Name = "Weight To")]
        public int? WeightTo { get; set; }

        [Required]
        [Display(Name = "Name")]
        public string Name { get; set; }
    }
}

查看

@model HelloWorldMvcApp.SampleModel
@{
    Layout = null;
}


                @using (Html.BeginForm())
                {

                @Html.ValidationSummary()

                    <div class="form-group">
                        @Html.LabelFor(m => m.WeightFrom)
                        @Html.TextBoxFor(m => m.WeightFrom, new {@class="form-control"}) 
                        @Html.ValidationMessageFor(m => m.WeightFrom)
                    </div>

                    <div class="form-group">
                        @Html.LabelFor(m => m.WeightTo)
                        @Html.TextBoxFor(m => m.WeightTo, new {@class="form-control"}) 
                        @Html.ValidationMessageFor(m => m.WeightTo)
                    </div>

                    <div class="form-group">
                        @Html.LabelFor(m => m.Name)
                        @Html.TextBoxFor(m => m.Name, new {@class="form-control"}) 
                        @Html.ValidationMessageFor(m => m.Name)
                    </div>

                    <button type="submit" class="btn btn-success submit">Save</button>
                }