[英]Required DataAnnotations needs BeginForm to fire validation in MVC5
[英]How create a dynamic DataAnnotations Attribute for validation on MVC5 (globalization)?
我將ef6和mvc5 一起使用。 我的項目需要多種語言 。 因此,我需要創建一個DataAnnotations屬性來驗證這些字段。
例如:我有一個Id屬性:
public int Id { get; set; }
為了驗證,我需要添加注釋,例如
[Display("User Id")]
Required(ErrorMessage = "Please input the Id")
public int Id { get; set; }
但是我需要使用多種語言,因此我創建了一個新的DataAnnotations屬性( https://stackoverflow.com/a/2432520/1900498 ):
public class LocalizedDisplayAttribute : DisplayNameAttribute
{
public LocalizedDisplayAttribute(string resourceId)
: base(GetMessageFromResource(resourceId))
{ }
private static string GetMessageFromResource(string resourceId)
{
// TODO: Return the string from the resource file
}
}
它工作正常,但是會緩存結果,然后在會話更改時(我正在使用會話保存用戶網站頁面的語言模式。例如1表示英語,0表示其他語言),它仍然沒有更改,這對於我。
第二個問題是:我不知道如何重寫RequiredAttribute以便讓用戶知道,某些字段不能為空。
但我也發現還有另一個問題,看起來我需要重寫有關數字字段的消息……(xx字段必須為數字)
因此,有什么方法可以重寫驗證規則,讓我確定“必需”,“范圍”,“數字...”的錯誤消息,它將緩存它,但是當會話更改時,它將再次讀取?
例如:
// if session changed rewrite rule message for current language
if (session["language"].ToString() != LastLanguage)
{
if (session["language"].ToString() == "1")
//English
{
RequiredMessage = "the field {0} must be required";
NumericMessage = "the field {0} must be a number";
LastLanguage = 1;
} else{
// other language
RequiredMessage = "xx xx {0} xxxxxxxxx";
NumericMessage = "xx xx {0} xxxxxxxxxx";
LastLanguage = 0;
}
}
當然, 不僅是驗證消息 ,我也需要全球化字段顯示名稱 。
DataAnnotation
已經提供了全球化支持:
[Display(ResourceType = typeof(Resource), Name = "Test")]
[Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "TestRequired")]
public string Test { get; set; }
更改global.asax
的當前文化
private void Application_AcquireRequestState(object sender, EventArgs e)
{
if (Context != null && Context.Session != null)
{
string language = Context.Session["language"] as string;
if (language != null)
{
Thread.CurrentThread.CurrentCulture = new CultureInfo(language);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(language);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.