值类型的自定义验证消息

值类型的自定义验证消息

本文介绍了ASP.NET MVC - 值类型的自定义验证消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 UpdateModel 或 TryUpdateModel 时,MVC 框架足够智能,可以知道您是否尝试将 null 传入值类型(例如,用户忘记填写所需的出生日字段).

When I use UpdateModel or TryUpdateModel, the MVC framework is smart enough to know if you are trying to pass in a null into a value type (e.g. the user forgets to fill out the required Birth Day field) .

不幸的是,我不知道如何覆盖默认消息需要一个值".在摘要中加入更有意义的内容(请输入您的出生日期").

Unfortunately, I don't know how to override the default message, "A value is required." in the summary into something more meaningful ("Please enter in your Birth Day").

必须有一种方法可以做到这一点(无需编写过多的变通代码),但我找不到.有什么帮助吗?

There has to be a way of doing this (without writing too much work-around code), but I can't find it. Any help?

编辑

此外,我想这也是无效转换的问题,例如BirthDay = "你好".

Also, I guess this would also be an issue for invalid conversions, e.g. BirthDay = "Hello".

推荐答案

通过扩展 DefaultModelBinder 来制作你自己的 ModelBinder:

Make your own ModelBinder by extending DefaultModelBinder:

public class LocalizationModelBinder : DefaultModelBinder

覆盖 SetProperty:

Override SetProperty:

        base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);

        foreach (var error in bindingContext.ModelState[propertyDescriptor.Name].Errors.
            Where(e => IsFormatException(e.Exception)))
        {
            if (propertyDescriptor.Attributes[typeof(TypeErrorMessageAttribute)] != null)
            {
                string errorMessage =
                    ((TypeErrorMessageAttribute)propertyDescriptor.Attributes[typeof(TypeErrorMessageAttribute)]).GetErrorMessage();
                bindingContext.ModelState[propertyDescriptor.Name].Errors.Remove(error);
                bindingContext.ModelState[propertyDescriptor.Name].Errors.Add(errorMessage);
                break;
            }
        }

添加函数bool IsFormatException(Exception e)来检查异常是否为FormatException:

Add the function bool IsFormatException(Exception e) to check if an Exception is a FormatException:

if (e == null)
            return false;
        else if (e is FormatException)
            return true;
        else
            return IsFormatException(e.InnerException);

创建一个属性类:

[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = false)]
public class TypeErrorMessageAttribute : Attribute
{
    public string ErrorMessage { get; set; }
    public string ErrorMessageResourceName { get; set; }
    public Type ErrorMessageResourceType { get; set; }

    public TypeErrorMessageAttribute()
    {
    }

    public string GetErrorMessage()
    {
        PropertyInfo prop = ErrorMessageResourceType.GetProperty(ErrorMessageResourceName);
        return prop.GetValue(null, null).ToString();
    }
}

将属性添加到您要验证的属性:

Add the attribute to the property you wish to validate:

[TypeErrorMessage(ErrorMessageResourceName = "IsGoodType", ErrorMessageResourceType = typeof(AddLang))]
    public bool IsGood { get; set; }

AddLang 是一个 resx 文件,IsGoodType 是资源的名称.

AddLang is a resx file and IsGoodType is the name of the resource.

最后将其添加到 Global.asax.cs Application_Start 中:

And finally add this into Global.asax.cs Application_Start:

ModelBinders.Binders.DefaultBinder = new LocalizationModelBinder();

干杯!

这篇关于ASP.NET MVC - 值类型的自定义验证消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 22:19