在我的班上,我有..
inline
在我看来..
public class MyModel
{
[MaxLength(30)]
public string Name { get; set; }
}
我的String.cshtml
@Html.AntiForgeryToken()
@Html.EditorForModel()
答案 0 :(得分:1)
您可以使用AdditionalMetadata属性代替StringLength属性。
[AdditionalMetadata("MaxLength", 30)]
public string Name { get; set; }
您的自定义编辑器模板(String.cshtml):
@{
string max = ViewData.ModelMetadata.AdditionalValues.ContainsKey("MaxLength")
? ViewData.ModelMetadata.AdditionalValues["MaxLength"].ToString() : null;
}
@Html.TextBox("", Model, new { maxlength = max })
然后你可以使用:
@Html.EditorFor(m => m.Name)
答案 1 :(得分:0)
以下是从属性中获取属性的一些基本代码。
// 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
}