We have localised strings in the database and would like to know if extending the ASP.NET Resource Provider Model would work with the ASP.NET MVC 3 Razor view engine.
Kindly let me know if ASP.NET MVC 3 Razor view engine supports retrieving localized strings from the database once we have extended the ASP.NET Resource Provider model. Or does it work only with Classic ASP.NET and not with ASP.NET MVC.
Thank you
Satyaprakash J
The cleanest solution I've found so far is: http://www.codeproject.com/Tips/514321/A-Simple-and-Effective-Way-to-Localize-ASP-Net-MVC.
Comments/Feedback are welcomed.
Edit 1: Based on comments, I added code examples and used the link as reference.
I created a customDataAnnotationsProvider class:
public class CustomDataAnnotationsProvider: DataAnnotationsModelMetadataProvider
{
private ResourceManager resourceManager = new ResourceManager();
protected override ModelMetadata CreateMetadata(
IEnumerable<Attribute> attributes,
Type containerType,
Func<object> modelAccessor,
Type modelType,
string propertyName)
{
string key = string.Empty;
string localizedValue = string.Empty;
foreach (var attr in attributes)
{
if (attr != null)
{
if (attr is DisplayAttribute)
{
key = ((DisplayAttribute)attr).Name;
if (!string.IsNullOrEmpty(key))
{
localizedValue = resourceManager.GetLocalizedText(key);
((DisplayAttribute)attr).Name = localizedValue;
}
}
else if (attr is ValidationAttribute)
{
key = ((ValidationAttribute)attr).ErrorMessage;
if (!string.IsNullOrEmpty(key))
{
localizedValue = resourceManager.GetLocalizedText(key);
((ValidationAttribute)attr).ErrorMessage = localizedValue;
}
}
}
}
return base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
}
}
Then I referenced the custom provider on ApplicationStart in Global.asax
ModelMetadataProviders.Current = new Project.Web.Helpers.CustomDataAnnotationsProvider();
You do not have to change your model and can use the Display annotation:
[Display(Name = "CustomerAccountNumber")]
public string CustomerAccountNumber { get; set; }
You are in luck because Rick have already done it for you!
Westwind.Globalization Data Driven Resource Provider for ASP.NET