[英]Global Resources in ASP.Net MVC Model ErrorMessage Attribute
I am creating web application in ASP.Net MVC 5. 我正在ASP.Net MVC 5中创建Web应用程序。
I need to add user defined languages. 我需要添加用户定义的语言。 (So, it can work in any language). (因此,它可以使用任何语言工作)。
I have added English text/messages in resources file. 我在资源文件中添加了英文文本/消息。
While, for other languages , resources will be generated run time in App_GlobalResources folder. 而对于其他语言,资源将在App_GlobalResources文件夹中生成运行时。
With this custom resources, I can able to show labels (, buttons etc.) as per selected language. 使用此自定义资源,我可以按照所选语言显示标签(,按钮等)。
But, I have issue with ErrorMessage , which is given as attribute in properties of model. 但是,我对ErrorMessage有问题,它是在模型属性中作为属性给出的。
Model classes are in class library, and reference of class library project is added in MVC. 模型类在类库中,而类库项目的引用在MVC中添加。
So, can't access resources from App_GlobalResources folder. 因此,无法访问App_GlobalResources文件夹中的资源。
And, if I add resources under Project of model class, I can give customize message with following code. 并且,如果我在模型类的Project下添加资源,则可以使用以下代码给出自定义消息。
[Required(ErrorMessage = "*")]
[System.Web.Mvc.Compare("Password", ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "PasswordCompare")]
public string ConfirmPassword { get; set; }
But, with this code, I can't use App_GlobalResources. 但是,使用此代码,我无法使用App_GlobalResources。
What will be solution in this scenario? 在这种情况下将有什么解决方案?
Finally, I got solution: 最后,我得到了解决方案:
Created custom attribute class. 创建自定义属性类。
[Required(ErrorMessage = "*")]
[CompareCustomAttribute("Password", ClassKey = "Resources", ResourceKey = "PasswordCompare")]
public string ConfirmPassword { get; set; }
Custom Attribute class is inheriting CompareAttribute class. 自定义属性类继承了CompareAttribute类。
public sealed class CompareCustomAttribute : System.Web.Mvc.CompareAttribute
{
public CompareCustomAttribute(string otherProperty)
: base(otherProperty)
{
}
public string ResourceKey { get; set; }
public string ClassKey { get; set; }
public override string FormatErrorMessage(string name)
{
return Convert.ToString(HttpContext.GetGlobalResourceObject(this.ClassKey, this.ResourceKey));
}
}
In overridden FormatErrorMessage method, I have put code to get customized error message from Global Resources. 在重写的FormatErrorMessage方法中,我放入了从全局资源中获取自定义错误消息的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.