How to read property data annotation value in .NET MVC

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

    @using System.ComponentModel.DataAnnotations
    @model string
    @{
        var htmlAttributes = ViewData["htmlAttributes"] ?? new { @class = "checkbox-inline" };
    
        var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
    
        if (!attributes.ContainsKey("maxlength"))
        {
            var metadata = ViewData.ModelMetadata;
            var prop = metadata.ContainerType.GetProperty(metadata.PropertyName);
            var attrs = prop.GetCustomAttributes(false);
            var maxLength = attrs.OfType().FirstOrDefault();
            if (maxLength != null)
            {
                attributes.Add("maxlength", maxLength.Length.ToString());
            }
            else
            {
                var stringLength = attrs.OfType().FirstOrDefault();
    
                if (stringLength != null)
                {
                    attributes.Add("maxlength", stringLength.MaximumLength.ToString());
                }
            }
        }
    
    }
    
    @Html.TextBoxFor(m => m, attributes)
    

提交回复
热议问题