Search code examples
asp.net-mvcasp.net-mvc-4razormvc-editor-templates

Get MaxLength value in .cshtml template


In my class I have..

public class MyModel
{
    [MaxLength(30)]
    public string Name { get; set; }
}

In my view..

@Html.AntiForgeryToken()
@Html.EditorForModel()

And my String.cshtml

@model string
@{ 
    // How to cetn MaxValue here ??
}

@Html.TextBox(Html.IdForModel().ToString(), Model, new { @class= "text-box single-line", placeholder=ViewData.ModelMetadata.Watermark })

Solution

  • Here is some basic code to get an attribute off a property.

    // use a nullable int to remember (or use a regular int and set a default, whatever your use-case is)
    int? maxLength;
    PropertyInfo[] props = typeof(MyModel).GetProperties();
    foreach (PropertyInfo prop in props)
    {
        object[] attrs = prop.GetCustomAttributes(true);
        foreach (object attr in attrs)
        {
            MaxLengthAttribute maxLengthAttr = attr as MaxLengthAttribute;
            if (maxLengthAttr != null &&  prop.Name.Equals("Name"))
            {
    
                maxLength = maxLengthAttr.Length
            }
        }
    }
    
    // check to make sure you got a value. opti
    if (maxLength.HasValue)
    {
    // whatever you want to do
    }