Search code examples
c#asp.net-coreasp.net-core-tag-helpers

Expression in ASP.NET Core TagHelpers


In TagHelpers we usually have a property called asp-for to connect the TagHelper to a Model property.

I created a custom TagHelper, and added a property like a asp-for:

    [HtmlTargetElement("myinput", TagStructure = TagStructure.WithoutEndTag)]
    public class MyInputTagHelper : TagHelper {
        public ModelExpression Field { get; set; }
    }

Normally, if the bound model is a complex type with subclasses and I need the full path to that property, I can get the full access path by evaluating System.Linq.Expressions.Expression. How can I achive this with ModelExpression?

I Have a model:

public class PersonVM
{
    public Person Person { get; set; }
}

and in .cshtml:

@model PersonVM

<myinput field="Person.PersonAddress.City"/>

In the TagHelper MyInputTagHelper, I need the full request path. In this example it would be "Person.PersonAddress.City". All I could get is "City" via Field.Metadata.PropertyName.


Solution

  • Ok I got it, the original expression is saved in

    ModelExpression.Name