vendredi 2 juillet 2021

How can extract Custom Property value from lambda expression?

I have the following class definition

Person.cs

class Person {

  [Column("first_name")]
  public string FirstName { get; set; }

  [Column("last_name")]
  public string LastName { get; set; }
}

I wrote an HTML Helper extension to extract the ColumnAttribute value from a given instance. However, it does not work as I expect.

Here is what I tried:

Index.cshtml

@model Person
<p>ColumnName is @Html.ColumnNameFor( model => model.FirstName )</p>

HtmlExtensions.cs (public static class)

public static string ColumnNameFor<T, P>(this HtmlHelper<T> helper, Expression<Func<T, P>> expression)
{
    var name = ExpressionHelper.GetExpressionText(expression);
    var metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);

    // this line causes a runtime error:
    //  Sequence contains no elements
    var attr = (ColumnAttribute)metadata.GetType().GetCustomAttributes(typeof(ColumnAttribute), false).First();
            
  return attr.Name;    // ColumnAttribute stores the value in .Name
}

For the record, I am able to extract the value using GetCustomAttributes, provided that I pass a reference to the property, which I think will make the code in the View look very different from the built in ASP MVC code for Html.TextBoxFor and Html.DisplayFor, etc.





Aucun commentaire:

Enregistrer un commentaire