c# - MVC 自定义验证工作但不显示错误

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

我在 MVC 版本 5 中遇到自定义验证问题。

我有下面的代码作为验证器。

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace PortalWebsite.Common
{
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    public class GreaterThanAttribute : ValidationAttribute, IClientValidatable
    {
        public string OtherPropertyName { get; private set; }
        public bool AllowEquality { get; private set; }

        public GreaterThanAttribute(string otherPropertyName, bool allowEquality = true)
        {
            AllowEquality = allowEquality;
            OtherPropertyName = otherPropertyName;
        }


        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var result = ValidationResult.Success;
            var otherValue = validationContext.ObjectType.GetProperty(OtherPropertyName)
                .GetValue(validationContext.ObjectInstance, null);
            if (value != null)
            {
                if (value is DateTime)
                {

                    if (otherValue != null)
                    {
                        if (otherValue is DateTime)
                        {
                            if (!OtherPropertyName.ToLower().Contains("DateTo"))
                            {
                                if ((DateTime)value > (DateTime)otherValue)
                                {
                                    result = new ValidationResult(ErrorMessage);
                                }
                            }
                            else
                            {
                                if ((DateTime)value < (DateTime)otherValue)
                                {
                                    result = new ValidationResult(ErrorMessage);
                                }
                            }
                            if ((DateTime)value == (DateTime)otherValue && !AllowEquality)
                            {
                                result = new ValidationResult(ErrorMessage);
                            }
                        }
                    }
                }
            }
            return result;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = ErrorMessage,
                ValidationType = "comparedates"
            };
            rule.ValidationParameters["otherpropertyname"] = OtherPropertyName;
            rule.ValidationParameters["allowequality"] = AllowEquality ? "true" : "";
            yield return rule;
        }
    }
}

然后在我的 View 模型中,我有:

public int Id { get; set; }
public DateTime? NotificationDateTo { get; set; }
[Display(Name = "Notification Date")]
[GreaterThan("NotificationDateTo", ErrorMessage = "Start date cannot be before end date")]
public DateTime? NotificationDateFrom { get; set; }

此代码有效,并且 IsValid 的结果设置正确。我的问题是代码没有返回到调用 View 。它只是继续进行,就好像没有什么是无效的。

我的观点是这样的(节选):

@using (Html.BeginForm("SearchResults", "Claims", new { id = 1 }, FormMethod.Get))
{
<div class="row">
    <div class="large-12 columns">
        <div class="row">
            <div class="small-3 columns">
                @Html.LabelFor(m => m.NotificationDateFrom, new { @class = "right inline" })
            </div>
            <div class="small-4 columns">
                @Html.TextBoxFor(model => model.NotificationDateFrom, new { autocomplete = "off", @class = "datePicker" })
                <span class="error">@Html.ValidationMessageFor(m => m.NotificationDateFrom)</span>
            </div>
            <div class="small-1 columns">
             and
            </div>
            <div class="small-4 columns">
                @Html.TextBoxFor(model => model.NotificationDateTo, new { autocomplete = "off", @class = "datePicker" })
                <span class="error">@Html.ValidationMessageFor(m => m.NotificationDateTo)</span>
            </div>
        </div>
    </div>
</div>
}

最佳答案

在您的 POST 方法中,您需要检查 ModelState.IsValid 属性,如果无效,则返回将显示错误消息的 View

public ActionResult SearchResults(yourViewModel model)
{
  if (!ModelState.IsValid)
  {
    return View(model);
  }
  // save and redirect

旁注:除非客户端验证被禁用,否则您不应该点击 POST 方法,这表明您没有包含与您的 GreaterThanAttribute 关联的验证脚本。您需要包含 2 个将规则添加到验证器的脚本

$.validator.addMethod(...) {

$.validator.unobtrusive.adapters.add(...) {

除非包含这些,否则在您的属性中实现 IClientValidatable 毫无意义

关于c# - MVC 自定义验证工作但不显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34720854/

相关文章:

c# - Windows.Forms Visual Studio,如何直接在第一个窗口上打开第二个窗口?

c# - 如何禁止 child 访问 ASP.net MVC 中的父操作方法?

asp.net - IIS为ASP.NET MVC3文件(.cshtml)返回404

c# - ASP.NET:同步客户端和服务器端验证规则

C# Entity Framework 内存使用率高,内存泄漏?

c# - ASP.NET 突出显示选定的 MenuItem

c# - 无法在 Visual Studio 的 Crystal Report 中加载数据库信息

c# - 如何为泛型类编写 C# 扩展方法

asp.net-mvc - ASP.Net MVC 不显眼的日期范围验证

c# - 如何使用ModelState.IsValid通过条件在单个 View 中验证多个ViewModel