Tuesday, June 7, 2016

How to drive the LabelFor and ValidationMessageFor copy in an MVC app from a resource file.

Use these two attributes at your model and you can probably tell which is for which, eh?

using System.ComponentModel.DataAnnotations;
namespace Foo
{
   public class Bar
   {
      [Required(ErrorMessageResourceType = typeof(Resources.Resources),
            ErrorMessageResourceName = @"Baz")]
      [Display(ResourceType = typeof(Resources.Resources), Name = @"Qux")]
      public string Whatever { get; set; }
   }
}

 
 

Resources.Resources above suggests a file called Resources.resx in your resources project within your ASP.NET solution that also holds your MVC project. The model above should play nicely with Razor markup like so:

@Html.LabelFor(m => m.Whatever)
@Html.TextBoxFor(m => m.Whatever)
@Html.ValidationMessageFor(m => m.Whatever)

No comments:

Post a Comment