У меня есть модель (упрощенная по релевантности), подобная этой:
public abstract class TitleCreateModel : ICreateModel
{
[Required]
[MaxLength(400)]
public string TitleName { get; set; }
[Required]
[MaxLength(4)]
public DateTime ReleaseDate { get; set; }
[Required]
[MaxLength(5)]
public string Test { get; set; }
[Required]
[MaxLength(2)]
public int Wut { get; set; }
}
Затем у меня есть собственный вспомогательный класс HTML и класс расширения Expression (оба без ограничений):
public class InputHelper
{
public static HtmlString Input<T>(Expression<Func<T, Object>> expression, string id, string label)
{
var req = expression.GetAttribute<T, Object, RequiredAttribute>();
var max = expression.GetAttribute<T, Object, MaxLengthAttribute>();
var required = "";
var maxlength = "";
if(req!=null)
{
required = "req";
}
if(max!=null)
{
maxlength = "maxlength='" + max.Length + "'";
}
return new HtmlString("<div class=\"clearfix\"><label for=\""+id+"\">" + label + "</label>" +
"<div class=\"input\"><input id=\""+id+"\" class=\""+required+"\" type=\"text\" "+maxlength+"/></div></div>");
}
}
public static class ExpressionExtensions
{
public static TAttribute GetAttribute<TIn, TOut, TAttribute>(this Expression<Func<TIn, TOut>> expression) where TAttribute : Attribute
{
var memberExpression = expression.Body as MemberExpression;
if (memberExpression != null)
{
var attributes = memberExpression.Member.GetCustomAttributes(typeof(TAttribute), true);
return attributes.Length > 0 ? attributes[0] as TAttribute : null;
}
return null;
}
}
В моем скрипте Razor я выполняю следующие вызовы:
@(InputHelper.Input<string>(m => Model.Title.TitleName, "titlename", "Title Name"))
@(InputHelper.Input<string>(m => Model.Title.Test, "testfield", "Test Field"))
@(InputHelper.Input<int>(m => Model.Title.Wut, "tester", "Test Field 2"))
@(InputHelper.Input<DateTime>(m => Model.Title.ReleaseDate, "release_year", "Release Year"))
По какой-то причине метод GetAttribute находит только атрибуты для TitleName и Test, которые являются строковыми свойствами для TitleCreateModel.Он не может найти атрибуты для ReleaseDate и Wut, и я понятия не имею, почему.