[英]How to use non-static enum values with the DefaultValue data annotation?
[英]non-static ErrorMessage data annotation in MVC
我有一個可以用多種語言打開的網站,該網站的字符串是從產品所有者提供的XML文件中檢索的。
該模型包含許多字段,但是對於這個問題,我們僅查看FamilyName
public class RegisterViewModel
{
public Translation Translation { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "LastNameEnter")]
[Display(Name = "Last Name")]
public string FamilyName { get; set; }
}
我以前使用上述格式來獲取驗證,並在模型上的字段中提示所需的錯誤消息。 現在,盡管我們有一個幫助程序,它可以讀取XML文件並創建一個包含“ Item”列表的Translation對象,但每個Item都是具有其他一些屬性的字符串。
我試圖將模型上的字段更改為以下格式,但是由於我收到以下錯誤,因此無法正常工作:
非靜態字段需要對象引用。
[Required(ErrorMessage = Translation.Item.Find(x => x.Id == "FamilyName " && x.Type == "Required").Text)]
public string FamilyName { get; set; }
如何使用我的非靜態Translation
屬性設置錯誤消息。
在控制器的構造函數中設置了translation屬性。
編輯:
問題出在我的Translation
對象實例化依賴於請求中的查詢字符串。
string Language = !String.IsNullOrEmpty(Request.QueryString["l"])? Request.QueryString["l"]: "en-en";
model.Translation = RegistrationScriptHelper.Translation.GetRegistrationScript(Request).Find(x => x.Language == Language);
編輯2: Global.asax.cs:
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CustomRequiredAttribute),
typeof(RequiredAttributeAdapter));
輸出:
您需要編寫自己的屬性才能實現此目的。 這是一個例子:
public class MyReqAttribute : RequiredAttribute
{
private string _errorID;
public MyReqAttribute(string errorID)
{
_errorID=errorID;
}
public override string FormatErrorMessage(string name)
{
string language = !String.IsNullOrEmpty(HttpContext.Current.Request.QueryString["l"])? HttpContext.Current.Request.QueryString["l"]: "en-en";
var translation = RegistrationScriptHelper.Translation.GetRegistrationScript(HttpContext.Current.Request).Find(x => x.Language == language);
this.ErrorMessage = translation.Item.Find(x => x.Id == errorID
&& x.Type == "Required").Text;
return base.FormatErrorMessage(name);
}
}
然后在Global.asax.cs
文件中添加以下行:
protected void Application_Start()
{
// other codes here
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MyReqAttribute),
typeof(RequiredAttributeAdapter));
}
然后,您可以在模型中使用自己的屬性:
[MyReqAttribute("FamilyName")]
public string FamilyName { get; set; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.