更改ASP.NET MVC 3中的默认ModelState错误消息

时间:2011-02-23 12:14:21

标签: asp.net-mvc localization asp.net-mvc-3

我的资源文件位于单独的程序集MyApp.Resources.dll中。我可以毫无问题地使用资源,但是当我想更改(本地化)默认验证消息时会出现问题:

“{0}字段是必需的。”“值”{0}“对{1}无效。”

solution DefaultModelBinder.ResourceClassKey = "MyApp.Resources.Global";不起作用,因为它要求ResourceClassKey位于Web项目的App_GlobalResources文件夹下。

对我来说应该解决什么问题?

此致

2 个答案:

答案 0 :(得分:5)

我找到了这种情况的解决方案(当资源处于单独的程序集中时)。

要使其正常工作,您应该创建自定义ResourceProviderFactory并将其注册为<globalization> web.config部分中的默认ResourceProviderFactoryType。

设置本地化

// Modify web.config in run-time and setup custom ResourceProviderFactory
var globalization = WebConfigurationManager.GetSection("system.web/globalization") as GlobalizationSection;
var readonlyField = typeof(ConfigurationElement).GetField("_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
readonlyField.SetValue(globalization, false);
globalization.ResourceProviderFactoryType = typeof(ValidationResourceProviderFactory).FullName;

var resourcesClass = typeof(ValidationResources).FullName; 
DefaultModelBinder.ResourceClassKey = resourcesClass;
ValidationExtensions.ResourceClassKey = resourcesClass;

<强> ValidationResourceProviderFactory

public sealed class ValidationResourceProviderFactory: System.Web.Compilation.ResourceProviderFactory
{
    public ValidationResourceProviderFactory()
    {
    }

    public override IResourceProvider CreateGlobalResourceProvider(string classKey)
    {
        return new GlobalResourceProvider(classKey);
    }

    public override IResourceProvider CreateLocalResourceProvider(string virtualPath)
    {
        throw new NotImplementedException("Local resources are not supported yet");
    }
}

<强> GlobalResourceProvider

public class GlobalResourceProvider : IResourceProvider
{
    public GlobalResourceProvider(string classKey)
    {
        Throw.IfBadArgument(() => String.IsNullOrEmpty(classKey), "classKey");

        var type = Type.GetType(classKey, false);
        if (type == null)
        {
            var asmName = classKey;
            var className = classKey;
            while(asmName.IndexOf(".") > -1 && type == null) 
            {
                asmName = asmName.Substring (0, asmName.LastIndexOf("."));
                className = classKey.Substring(asmName.Length + 1);
                type = Type.GetType(classKey + "," + asmName, false);
            }
        }

        Throw.IfNullArgument(type, "type");

        Manager = CreateResourceManager(classKey, type.Assembly);
    }

    public ResourceManager Manager { get; set; }

    #region IResourceProvider implementation

    public IResourceReader ResourceReader { get; set; }

    public object GetObject(string resourceKey, CultureInfo culture)
    {
        return Manager.GetObject(resourceKey, culture);
    }

    #endregion

    private ResourceManager CreateResourceManager(string classKey, Assembly assembly)
    {
        return new ResourceManager(classKey, assembly);
    }
}

<强> UPD

RESX for ValidationResources

只需将新资源类添加为ValidationResources并将提供的XML放在那里

<?xml version="1.0" encoding="utf-8"?>
<root>
  <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
   <!--  Schema definited removed -->
  </xsd:schema>
  <resheader name="resmimetype">
    <value>text/microsoft-resx</value>
  </resheader>
  <resheader name="version">
    <value>2.0</value>
  </resheader>
  <resheader name="reader">
    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
  <resheader name="writer">
    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
  <data name="Accept" xml:space="preserve">
    <value>Please enter a value with a valid mimetype.</value>
  </data>
  <data name="Creditcard" xml:space="preserve">
    <value>Please enter a valid credit card number.</value>
  </data>
  <data name="Date" xml:space="preserve">
    <value>Please enter a valid date.</value>
  </data>
  <data name="DateISO" xml:space="preserve">
    <value>Please enter a valid date (ISO).</value>
  </data>
  <data name="DateTime" xml:space="preserve">
    <value>Please enter a valid date and time.</value>
  </data>
  <data name="Digits" xml:space="preserve">
    <value>Please enter only digits.</value>
  </data>
  <data name="Email" xml:space="preserve">
    <value>Please enter a valid email address.</value>
  </data>
  <data name="EqualTo" xml:space="preserve">
    <value>Please enter the same value again.</value>
  </data>
  <data name="FieldMustBeDate" xml:space="preserve">
    <value>Please enter a valid date for "{0}".</value>
    <comment>Localization for legacy MVC ClientDataTypeModelValidatorProvider</comment>
  </data>
  <data name="FieldMustBeNumeric" xml:space="preserve">
    <value>Please enter a valid number for "{0}".</value>
    <comment>Localization for legacy MVC ClientDataTypeModelValidatorProvider</comment>
  </data>
  <data name="InvalidPropertyValue" xml:space="preserve">
    <value>Invalid property value: {0}</value>
  </data>
  <data name="Max" xml:space="preserve">
    <value>Please enter a value less than or equal to {0}.</value>
  </data>
  <data name="MaxLength" xml:space="preserve">
    <value>Please enter no more than {0} characters.</value>
  </data>
  <data name="Min" xml:space="preserve">
    <value>Please enter a value greater than or equal to {0}.</value>
  </data>
  <data name="MinLength" xml:space="preserve">
    <value>Please enter at least {0} characters.</value>
  </data>
  <data name="Number" xml:space="preserve">
    <value>Please enter a valid number.</value>
  </data>
  <data name="PropertyValueInvalid" xml:space="preserve">
    <value>The value "{0}" is invalid for the property "{1}"</value>
    <comment>Localization for legacy MVC DefaultModelBinder</comment>
  </data>
  <data name="PropertyValueRequired" xml:space="preserve">
    <value>The "{0}" field is required.</value>
    <comment>Localization for legacy MVC DefaultModelBinder</comment>
  </data>
  <data name="Range" xml:space="preserve">
    <value>Please enter a value between {1} and {2}.</value>
  </data>
  <data name="RangeClient" xml:space="preserve">
    <value>Please enter a value between {0} and {1}.</value>
  </data>
  <data name="RangeLength" xml:space="preserve">
    <value>Please enter a value between {0} and {1} characters long.</value>
  </data>
  <data name="Remote" xml:space="preserve">
    <value>Please fix this field.</value>
  </data>
  <data name="SignedInt" xml:space="preserve">
    <value>Please enter an integer value, sign allowed.</value>
  </data>
  <data name="Time" xml:space="preserve">
    <value>Please enter a valid time.</value>
  </data>
  <data name="UnsignedInt" xml:space="preserve">
    <value>Please enter a positive integer value.</value>
  </data>
  <data name="Url" xml:space="preserve">
    <value>Please enter a valid URL.</value>
  </data>
  <data name="ValueNull" xml:space="preserve">
    <value>&lt;null&gt;</value>
  </data>
</root>

答案 1 :(得分:0)

您可以设置DefaultModelBinder上的静态属性,这些属性将更改错误消息的本地化...

http://forums.asp.net/p/1512140/3608427.aspx

  

在中创建一个全局资源类   App_GlobalResources,并设置   DefaultModelBinder.ResourceClassKey to   这个类的名称(例如,   如果您制作了“Messages.resx”,则设置   ResourceClassKey为“Messages”)。

     

您可以覆盖两个字符串   在MVC 2中:

     

的字符串值   当使用“PropertyValueInvalid”时   用户输入的数据不是   与数据类型兼容(for   例如,输入“abc”表示   整数字段)。默认消息   对于这个:“值'{0}'不是   对{1}有效。“字符串值为   当使用“PropertyValueRequired”时   用户没有输入任何数据   不可空的字段(for   例如,一个整数字段)。该   默认消息是:“一个值   是必需的。“