获取 .cshtml 模板中的 MaxLength 值
Get MaxLength value in .cshtml template
在我的 class 我有..
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):
@{
string max = ViewData.ModelMetadata.AdditionalValues.ContainsKey("MaxLength")
? ViewData.ModelMetadata.AdditionalValues["MaxLength"].ToString() : null;
}
@Html.TextBox("", Model, new { maxlength = max })
然后你可以使用:
@Html.EditorFor(m => m.Name)
在我的 class 我有..
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):
@{
string max = ViewData.ModelMetadata.AdditionalValues.ContainsKey("MaxLength")
? ViewData.ModelMetadata.AdditionalValues["MaxLength"].ToString() : null;
}
@Html.TextBox("", Model, new { maxlength = max })
然后你可以使用:
@Html.EditorFor(m => m.Name)