Search code examples
c#asp.net-coretag-helperspropertyinfo

How to Read TagHelper property text value?


i want to get string text of assigned property name? for example: I have a TagHelper:

public class CustomControl: TagHelper
{
[HtmlAttributeName("Items")]
public IEnumerable<object> DataItems { get; set; }

public async override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
   string stringText=datatitems.GetType()??? //it should result "listDataBC"
}

then used on any page :

<customcontrol Items="listDataBC"/>

Thank you


Solution

  • You could use the ModelExpression as parameter and use "@listDataBC" to get the name and values.
    CustomControl.cs

        public class CustomControl : TagHelper
        {
            [HtmlAttributeName("Items")]
            public ModelExpression expression { get; set; }
    
            public async override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
            {
            
                var name = expression.Name;
                var value = expression.Model; 
            }
        }
    

    Index.cshtml

    @{
        var listDataBC = new List<object>()
        {
            new {Name="tom"},
            new {Name="kite"}
        };
    }
    <custom-control Items="@listDataBC"></custom-control>
    

    Test result enter image description here