How to read property data annotation value in .NET MVC

前端 未结 6 1557
独厮守ぢ
独厮守ぢ 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:18

    An much simpler solution is to implement a custom DataAnnotationsModelMetadataProvider like this:

    internal class CustomModelMetadataProvider : DataAnnotationsModelMetadataProvider
    {
        protected override ModelMetadata CreateMetadata(IEnumerable attributes, Type containerType, Func modelAccessor, Type modelType, string propertyName)
        {
            ModelMetadata modelMetadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
    
            var maxLengthAttribute = attributes.OfType().SingleOrDefault();
            if (maxLengthAttribute != null)
            {
                modelMetadata.AdditionalValues.Add("maxLength", maxLengthAttribute.Length);
            }
            return modelMetadata;
        }
    }
    
    
    

    In the template you can simply use:

    object maxLength;
    ViewData.ModelMetadata.AdditionalValues.TryGetValue("maxLength", out maxLength);
    

    提交回复
    热议问题