c# - How create a dynamic DataAnnotations Attribute for validation on MVC5 (globalization)? -
i'm using ef6 mvc5. project need multiple language. need create dataannotations attribute validation these field.
for example: have id property:
public int id { get; set; }
for validation need add together annotations like
[display("user id")] required(errormessage = "please input id") public int id { get; set; }
but need utilize multiple language , create new dataannotations attribute(http://stackoverflow.com/a/2432520/1900498):
public class localizeddisplayattribute : displaynameattribute { public localizeddisplayattribute(string resourceid) : base(getmessagefromresource(resourceid)) { } private static string getmessagefromresource(string resourceid) { // todo: homecoming string resource file } }
it works fine , cache result, when session changed(i'm utilize session save user website page language mode. 1 mean english, 0 mean other language), still not change, problem me.
second problem is: don't know how rewrite requiredattribute allow user know , field can't empty.
but find there problem , looks need rewrite message numeric field......(xx field must numeric)
so there way can rewrite validation rule, allow me decide error message required, range, numeric...... , cache when session changed, read again?
for example:
// if session changed rewrite rule message current language if (session["language"].tostring() != lastlanguage) { if (session["language"].tostring() == "1") //english { requiredmessage = "the field {0} must required"; numericmessage = "the field {0} must number"; lastlanguage = 1; } else{ // other language requiredmessage = "xx xx {0} xxxxxxxxx"; numericmessage = "xx xx {0} xxxxxxxxxx"; lastlanguage = 0; } }
of course, not validation message, need globalization field display name too.
dataannotation
provides globalization support:
[display(resourcetype = typeof(resource), name = "test")] [required(errormessageresourcetype = typeof(resource), errormessageresourcename = "testrequired")] public string test { get; set; }
to alter current civilization in global.asax
private void application_acquirerequeststate(object sender, eventargs e) { if (context != null && context.session != null) { string language = context.session["language"] string; if (language != null) { thread.currentthread.currentculture = new cultureinfo(language); thread.currentthread.currentuiculture = new cultureinfo(language); } } }
c# asp.net .net asp.net-mvc
No comments:
Post a Comment