Getting Attribute from Parameter in HTML Helper

So, let's say I have a small model object that contains the required string and has a maximum length of 50:

public class ObjectModel { [Required] [MaxLength(50)] public string Name { get; set; } } 

I need to create a special HTML helper where I can pass a string (in this case ObjectModel.Name), and if necessary, create an HTML input element with the class "required".

Now I am trying to work with:

  public static HtmlString Input(string label) { return new HtmlString("<input type=\"text\" />"); } 

So, in my Razor view, if I do something like @InputHelper.Input(Model.Name) , I cannot access the attributes. My question is, how can I structure my HTML helper class to accept the Model property along with my attributes?

So, I have made further progress, but I still have not enough experience to navigate through the expressions to get what I want. Right now I have:

@InputHelper.Input(m => Model.Title.TitleName, "titlename2", "Title Name")

The second and third parameters are not relevant to this issue. And in the helper method, I have:

public static HtmlString Input(Expression<Func<string, Object>> expression, string id, string label)

But when I move on to debugging the code, there are so many objects and properties that I don’t know where my Required and MaxLength attributes are, even if they are there.

+4
source share
2 answers

You can get the Required and MaxLength attributes using the following extension method:

 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; var attributes = memberExpression.Member.GetCustomAttributes(typeof(TAttribute), true); return attributes.Length > 0 ? attributes[0] as TAttribute : null; } } 

Then from your code you can:

 public static HtmlString Input(Expression<Func<string, Object>> expression, string id, string label) { var requiredAttribute = expression.GetAttribute<string, object, RequiredAttribute>(); if (requiredAttribute != null) { // some code here } } 
+2
source

You should see what they did with the .NET platform. Create a method that accepts the expression>, and then use the code to retrieve the property name from the helper:

0
source

Source: https://habr.com/ru/post/1381149/


All Articles