Databases Reference
In-Depth Information
[Required(ErrorMessage = “Product Name cannot be empty”)]
public string ProductName { get; set; }
Both the Validator class and the DynamicValidator control rely on the DisplayAttribute
and the ErrorMessage property of validation attributes when generating error messages. If
you chose to specify error messages explicitly, keep in mind that you might still need to
specify the DisplayAttribute for properties displayed in any dynamically generated pages
of your application.
In web applications with localization requirement, display names and error messages
cannot be hard-coded as string literals in the entity model. Data annotation attributes
support the traditional .NET approach to localization based on assembly resources. You
can define display names and error messages as string resources in a RESX file, typically
located in the same assembly where the entity classes themselves reside. Visual Studio
automatically generates a resource helper class based on the contents of the RESX file. For
each string resource, this class has a static property with the matching name, which looks
similar to the following pseudo-code:
public class Resources
{
public static string ProductNameDisplayName { get; }
public static string ProductNameRequiredErrorMessage { get; }
}
For a data annotation attribute to retrieve a string from resources, you need to specify the
type of the resource class and the name of the property that returns it. For the
DisplayAttribute , specify the type via its ResourceType property and the Name property,
which normally contains the actual string value but now specifies the name of the
resource property that returns it:
[Display(ResourceType = typeof( Resources ), Name = “ ProductNameDisplayName ”)]
public string ProductName { get; set; }
NOTE
Data annotation attributes use reflection to access string resources through a helper
class such the one just shown and assume that the class as well as its static proper-
ties have public visibility. By default, visibility of the generated resource class is
internal , which results in a runtime error in Dynamic Data pages. You can change this
using the Visual Studio resource designer.
Validation attributes also rely on the helper classes to retrieve error messages from string
resources. The base class, ValidationAttribute , defines two properties that allow you to
specify this information— ErrorMessageResourceType and ErrorMessageResourceName .
Here is how to change the RequiredAttribute applied to the ProductName property to
 
Search WWH ::




Custom Search