I would like to have a model with a dynamic label in the razor view that gets set at runtime but is based on a string from a resource file using string formatting.
Lets say I have a simple model with a single property
public class Simple
{
[Display(ResourceType = (typeof(Global)), Name = "UI_Property1")]
[Required(ErrorMessageResourceType = (typeof(Global)), ErrorMessageResourceName = "ERROR_Required")]
[StringLength(40, ErrorMessageResourceType = (typeof(Global)), ErrorMessageResourceName = "ERROR_MaxLength")]
public string Property1{ get; set; }
}
And the resource file has the following strings
UI_Property1 {0}
ERROR_Required Field {0} is required.
ERROR_MaxLength Maximum length of {0} is {1}
and I would like to do something like this in the razor view
@Html.LabelFor(m => m.Property1, "xyz", new { @class = "control-label col-sm-4" })
and the resulting view would show the field label as 'xyz' and the value 'xyz' would also be shown in the validation messages returned from the server model validation.
I have been looking at various ways of doing this with no luck. I have investigated overriding the DisplayAttribute but this is a sealed class.
I also looked at overriding the DisplayName attribute but this does not get picked up properly with the required validation messages. Plus I wasn't sure how to inject the dynamic text in to the attribute which I assume will need to be done in the attribute constructor.
I have also looked at writing a custom DataAnnotationsModelMetadataProvider but cannot see a way of using this to achieve what I want. This may be down to my lack of coding skills.
The 'xyz' string will come from a setting in the web.config file and does not need to be injected at the LabelFor command but can be injected somewhere else if it would make more sense.
If anyone can give me clue as to how I might achieve this that would be great.