本文介绍了在 .cshtml 模板中获取 MaxLength 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的课堂上我有..
public class MyModel
{
[MaxLength(30)]
public string Name { get; set; }
}
在我看来..
@Html.AntiForgeryToken()
@Html.EditorForModel()
还有我的 String.cshtml
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 })
推荐答案
这里是一些基本的代码,用于从属性中获取属性.
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
}
这篇关于在 .cshtml 模板中获取 MaxLength 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!