2013-03-07 26 views
6

Cách bản địa hóa các thông điệp kiểu dữ liệu trong MVC4 "Trường ngày phải là một ngày".Cách bản địa hóa các thông báo kiểu dữ liệu

<input data-val="true" data-val-date="The field Date be a date." id="Date" name="Date" value="" > 

tôi sử dụng:

public class LocalizedDataTypeAttributeAdapter : DataAnnotationsModelValidator<DataTypeAttribute> 

     { 
      public LocalizedDataTypeAttributeAdapter(ModelMetadata metadata, ControllerContext context, DataTypeAttribute attribute) : base(metadata, con 

text, attribute) 
     { 
      attribute.ErrorMessageResourceType = typeof(Localization.Global); 
      attribute.ErrorMessageResourceName = "PropertyDataFormat"; 
     } 

    } 

Cũng LocalizedDataTypeAttributeAdapter đăng ký trong Global.asax

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(DataTypeAttribute), typeof(LocalizedDataTypeAttributeAdapter)); 

Trả lời

1

Bạn cần phải viết lại ClientDataTypeModelValidatorProvider

Take it https://github.com/mono/aspnetwebstack/blob/master/src/System.Web.Mvc/ClientDataTypeModelValidatorProvider.cs

và thay đổi

private static string GetUserResourceString(ControllerContext controllerContext, string resourceName) 
     { 
      string result = null; 

      if (!String.IsNullOrEmpty(ResourceClassKey) && (controllerContext != null) && (controllerContext.HttpContext != null)) 
      { 
       //result = controllerContext.HttpContext.GetGlobalResourceObject(ResourceClassKey, resourceName, CultureInfo.CurrentUICulture) as string; 
       result = GlobalRes.ResourceManager.GetString(resourceName); 
      } 

      return result; 
     } 

Sau đó thiết lập nó như là DefaultModelBinder trong Application_Start trong Global.asax:

protected void Application_Start() 
{ 

    var existingProvider = ModelValidatorProviders.Providers.Single(x => x is ClientDataTypeModelValidatorProvider); 
    ModelValidatorProviders.Providers.Remove(existingProvider); 
    ModelValidatorProviders.Providers.Add(new myClientDataTypeModelValidatorProvider()); //!! 
    myClientDataTypeModelValidatorProvider.ResourceClassKey = typeof(GlobalRes).Name; 
    DefaultModelBinder.ResourceClassKey = typeof(GlobalRes).Name; 
} 
+0

GlobalRes tham chiếu là gì? Và MvcResources tham khảo? Làm ơn hãy nói cho tôi. Và bạn cũng buồn "Sau khi viết trong Global.asax" ĐỂ PHƯƠNG PHÁP? Đề nghị rất xấu. –

+1

@ CanÜrek GlobalRes có vẻ là tên lớp tài nguyên, giống với tên của tệp tài nguyên. Vì vậy, trong trường hợp này, tệp * .resx sẽ là 'GlobalRes.resx'. Thay thế 'GlobalRes' bằng tên của lớp tài nguyên của bạn. –

+0

Nhưng bất kể, điều này không làm việc trong MVC 5, tôi đã không tìm thấy một giải pháp làm việc duy nhất để có được nội địa hoá của các thông báo xác nhận được thực hiện, ít nhất là cho thông báo lỗi-ngày. Cái đó dường như được mã hóa cứng. Làm tốt lắm. –

Các vấn đề liên quan