How to read property data annotation value in .NET MVC

前端 未结 6 1564
独厮守ぢ
独厮守ぢ 2020-12-17 04:43

I Just starting out w/ ASP.NET MVC 3 and I am trying to render out the following HTML for the string properties on a ViewModel on the create/edit view.



        
6条回答
  •  不知归路
    2020-12-17 05:35

    A full code sample for tvanfosson's answer:

    Model:

    public class Product
    {
        public int Id { get; set; }
    
        [MaxLength(200)]
        public string Name { get; set; }
    

    EditorTemplates\String.cshtml

    @model System.String
    @{
        var metadata = ViewData.ModelMetadata;
        var prop = metadata.ContainerType.GetProperty(metadata.PropertyName);
        var attrs = prop.GetCustomAttributes(false);
    
        var maxLength = attrs.OfType().FirstOrDefault();
    }
    

    Editor Template:

    @model System.String
    @using System.ComponentModel.DataAnnotations;
    @using Brass9.Web.Mvc.EditorTemplateHelpers;
    @{
        var metadata = ViewData.ModelMetadata;
    
        var attrs = EditorTemplateHelper.GenerateAttributes(ViewData, new Delegate[] {
            new Func(len => "maxlength=" + len.MaximumLength),
            new Func(max => "maxlength=" + max.Length)
        });
    
        if (metadata.IsRequired)
        {
            attrs.Add("required");
        }
    
        string attrsHtml = String.Join(" ", attrs);
    }
    
    

    So you pass in an array of Delegates, and for each entry use a Func, and then return whatever HTML string you wanted for each attribute.

    This actually decouples well - you can map only the attributes you care about, you can map different sets for different parts of the same HTML, and the final usage (like @attrsHtml) doesn't harm readability of the template.

提交回复
热议问题