开发者

Decorate model fields with metadata from resource file

开发者 https://www.devze.com 2023-01-28 10:34 出处:网络
I would like to separate my attribute decoration(3-4 per field) by having them someplace else so that my code looks readable.
  • I would like to separate my attribute decoration(3-4 per field) by having them someplace else so that my code looks readable.
  • Also the arguments passed to some开发者_C百科 attributes should come from a resource file. EG:[Required("Cannot proceed without entering *field_Name*")] I need just [Required]

Possible duplicate of this question(on which i couldn't resist offering a bounty) : Default resource for data annotations.


To answer your first question, you can use buddy classes. For example, if you have a "User" model, then you can create a "UserMetadata" buddy class. You can then add attributes to properties in the buddy class instead of the main class. ASP.NET MVC fully supports this, and will use your buddy class for things like validation and display name. Here is how you declare a buddy class:

[MetadataType(typeof(UserMetadata))]
public class User
{
    public string Name { get; set; }
}

public class UserMetadata
{

    [Required]
    public object Name { get; set; }

}

Note that the property type in the buddy class can always be "object", because MVC doesn't look at the property type in buddy classes.

Note also that MetadataTypeAttribute can be found in the System.ComponentModel.DataAnnotations namespace.

For your second question, you can look at the answer that I posted here: Default resource for data annotations in ASP.NET MVC


For the first question, maybe you could try using Fluent Validation. You can hook it up to MVC by following these instructions.

For the second question, I've posted an answer here: Default resource for data annotations in ASP.NET MVC

0

精彩评论

暂无评论...
验证码 换一张
取 消