MVC Localization of Default Model Binder

后端 未结 3 398
北恋
北恋 2021-01-02 20:45

I am currently trying to figure out how to localize the error messages generated by MVC. Let me use the default model binder as an example, so I can explain the problem.

相关标签:
3条回答
  • 2021-01-02 21:14

    Have you tried: IDataErrorInfo property

    This article will help

    • Validating with the IErrorDataInfo Interface (C#)
    0 讨论(0)
  • 2021-01-02 21:33

    See http://forums.asp.net/p/1512140/3608427.aspx, scroll down to Brad Wilson's reply near the bottom of that page (Sat, Jan 09 2010, 3:20 PM). There are static properties on the DefaultModelBinder that you can set to localize the generic error messages.

    The reason a generic error message is used instead of your [Range] message is that [Range] provides a validation error message, but this particular case is a binding error. There's absolutely no way the framework can ever hope to convert the string "ten" to an Int32, so it can't even fire the [Range] validator. This is what the "PropertyValueInvalid" key as mentioned in that forum controls.

    0 讨论(0)
  • 2021-01-02 21:35

    In MVC3 do the following to change default messages:

    1. add the App_GlobalResources folder to your ASP.NET site
    2. add a new resource file, call it f.ex. MyResources.resx
    3. add these keys
      • PropertyValueRequired: A value is required.
      • PropertyValueInvalid: The value '{0}' is not valid for {1}.
    4. in Application_Start of global.asax.cs add the line DefaultModelBinder.ResourceClassKey = "MyResources";
    0 讨论(0)
提交回复
热议问题