0
votes

I am unable to make tag helper working ASP.Net core project in Visual Studio 2015. There is no compilation errors in the project. When I run the project the tag helper is not getting rendered. I put the break point in "Process" method in Tag helper, but it is not coming there. Please let me know how to make it work.

1.Included "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final" in "dependencies" section in "project.json" file.

2.Added @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers in _ViewImports.cshtml file.

3.Added below code in Index.cshtml

<table generate-rows="@Model.Count()" source-model="@Model"></table>

4.Tag helper code

using System.Collections;
using System.Text;
using System.Reflection;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Microsoft.AspNetCore.Mvc.ViewFeatures;

namespace MVC_TagHelper.CustomTagHelper
{
    [HtmlTargetElement("table",Attributes ="generate-rows,source-model")]
    public class TableTagHelper : TagHelper
    {
        [HtmlAttributeName("generate-rows")]
        public int RepeatCount { get; set; }
        [HtmlAttributeName("source-model")]
        public ModelExpression DataModel { get; set; }
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            IEnumerable model = DataModel.Model as IEnumerable;
            if (model == null)
                return;
            else
            {
                StringBuilder sb = new StringBuilder();
                foreach (var m in model)
                {
                    PropertyInfo[] properties = m.GetType().GetProperties();
                    string html = "<tr>";
                    for (int i = 0; i < properties.Length; i++)
                    {
                        html += "<td>" + m.GetType().GetProperty(properties[i].Name).GetValue(m, null) + "</td>";
                    }
                    html += "</tr>";
                    sb.Append(html);
                }
                output.Content.SetHtmlContent(sb.ToString());
            }
        }
    }
}
1

1 Answers

0
votes

Check _ViewImports.cshtml. Make sure it contains a reference to your tag helper class namespace:

@using MVC_TagHelper;
@addTagHelper *, MVC_TagHelper

I struggled with the same problem a while ago.