小编Ber*_*rnd的帖子

从Lambda Property Expression获取自定义属性

我正在使用ASP.NET MVC 2 Preview 2并编写了一个自定义的HtmlHelper扩展方法来使用表达式创建标签.TModel来自具有属性的简单类,属性可以具有定义验证要求的属性.我试图找出表达式在我的label方法中表示的属性上是否存在某个属性.

类和标签的代码是:

public class MyViewModel
{
    [Required]
    public string MyProperty { get; set; }
}

public static MvcHtmlString Label<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string label)
{
    return MvcHtmlString.Create(string.Concat("<label for=\"", expression.GetInputName(), "\">", label, "</label>"));
}

public static string GetInputName<TModel, TProperty>(this Expression<Func<TModel, TProperty>> expression)
{
    return expression.Body.ToString().Substring(expression.Parameters[0].Name.Length + 1);
}
Run Code Online (Sandbox Code Playgroud)

然后我会像这样称呼标签:

Html.Label(x => x.MyProperty, "My Label")
Run Code Online (Sandbox Code Playgroud)

有没有办法找出传递给Label方法的表达式值中的属性是否具有Required属性?

我发现如果它存在,执行以下操作确实可以获得属性,但我希望有更简洁的方法来实现这一点.

public static MvcHtmlString Label<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string label)
{
    System.Attribute.GetCustomAttribute(Expression.Property(Expression.Parameter(expression.Parameters[0].Type, expression.GetInputName()), expression.GetInputName()).Member, typeof(RequiredAttribute))

    return …
Run Code Online (Sandbox Code Playgroud)

c# lambda attributes

20
推荐指数
2
解决办法
2万
查看次数

标签 统计

attributes ×1

c# ×1

lambda ×1