Asp.net mvc 获取.cshtml模板中的MaxLength值

Asp.net mvc 获取.cshtml模板中的MaxLength值,asp.net-mvc,asp.net-mvc-4,razor,mvc-editor-templates,Asp.net Mvc,Asp.net Mvc 4,Razor,Mvc Editor Templates,在我的班上我有 public class MyModel { [MaxLength(30)] public string Name { get; set; } } 在我看来 @Html.AntiForgeryToken() @Html.EditorForModel() 还有我的String.cshtml @model string @{ // How to cetn MaxValue here ?? } @Html.TextBox(Html.IdForModel(

在我的班上我有

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

@Html.AntiForgeryToken()
@Html.EditorForModel()
还有我的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 })

下面是一些从属性中获取属性的基本代码

// 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
}

您可以使用AdditionalMetadata属性代替StringLength属性

[AdditionalMetadata("MaxLength", 30)]
public string Name { get; set; }
您的自定义编辑器模板(String.cshtml):

然后您可以使用:

@Html.EditorFor(m => m.Name)
@Html.EditorFor(m => m.Name)