Defining the CultureInfo of a property using DataAnnotation

流过昼夜 提交于 2019-12-11 10:57:45

问题


I'm working on a MVC4 application where there's a field with a Data Mask like 000000,00. Since the main culture of the project is pt-BR, this is correct and works as expected.

The problem is that some of our developers have their cultures set to english, and when submitting this to a server set as en-US, a validation error occurs, because the method expects 000000.00 instead of 000000,00.

I thought about making a js fix to check the browser language and change the mask accordingly, but if the browser is set to english and the server to portuguese it'd fail (some of our testers are in this exact scenario).

My plan B is to use DataAnnotation so the server knows the culture it should use when validating the input.

[MagicValidation('pt-BR'))]
public virtual double? myProp { get; set; }

Considering I can't assume the server will be in one set language, my doubts are:

Is my approach correct?
Is there any other easier way of doing it?
If I'm on the right track, is there an existing annotation that already does this?

Thanks in advance for your attention


回答1:


Have you tried to force the culture in your web.config like this:

<system.web>
    <globalization uiCulture="pt" culture="pt-BR"/>
</system.web>



回答2:


I ended up on using this custom model binder, using only a NumberFormatInfo as the second parameter of the Convert.ToDouble() (instead of a CultureInfo). Here's the NumberFormatInfo I used:

readonly NumberFormatInfo NumberFormatInfo = new NumberFormatInfo()
{
    NumberDecimalSeparator = ",",
    NumberGroupSeparator = ".",
    NumberGroupSizes = new int[] { 3 }
};

The rest is just a copy/paste of the linked solution



来源:https://stackoverflow.com/questions/23739534/defining-the-cultureinfo-of-a-property-using-dataannotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!