I have a ViewModel like this:
public class MyViewModel
{
[Display(Name = "One_Name", ResourceType = typeof(Resources.User.Resource1))]
public string One { get; set; }
[Display(Name = "Two_Name", ResourceType = typeof(Resources.User.Resource1))]
public string Two { get; set; }
}
Which is used on page 1, and works great (e.g pulls back the resource) when i do stuff like this:
@Html.LabelFor(model => model.One)
But i also want to use this ViewModel on page 2, but i wan’t to point the properties to a different resource file (e.g Resources.User.Resource2).
I don’t want to have to dupe the class, but i’d be open to some OO trick.
The problem is that the attribute arguments must be strings, constants, typeof or array expressions.
What’s the best way to solve this problem?
Yep, it does seem like MVC doesn’t support such a scenario. You can provide your own ResourceType class but it must have static properties (such as
public static string One_Nameandpublic static string Two_Namein your example) that return the display strings, and there is no elegant way to make it do what you want.But since
Html.LabelFordoesn’t do anything particularly earth-shattering, you could easily do without in a view. Just write your own<label>element and get the localized string directly, which is as easy as callingResourceManager.GetString. You could still useHtml.LabelForin most cases and only resort to writing your own labels in the (hopefully rare) cases where a certain view does need to vary the display text.