Is it possible to list all views within a project and their elements like below in ASP.NET Core MVC using C#?
Actually I want to do that with reflection in C#. Please give me a solution.
Area | Controller | View | Element | asp-for | Id | Name |
---|---|---|---|---|---|---|
CMMS | Equipments | Index | button | create | create | |
CMMS | Equipments | Create | input | Name | Name | |
CMMS | Equipments | Create | select | LocationId | ||
Production | Products | List | table | tblProductsList | ||
Production | Products | Edit | select | ProductTypeId |
An easy solution is to use htmlAgility pack to parse all the elements. I don't know how to achieve this using "reflection".
public class Info
{
public string Area { get; set; }
public string Controller { get; set; }
public string View { get; set; }
public string Element { get; set; }
public string aspfor { get; set; }
public string Id { get; set; }
public string Name { get; set; }
}
Non-area HomeController
(Just note that this code only search cshtml in "areas" folder)
public IActionResult Index()
{
var infos = new List<Info>();
var viewFiles = Directory.GetFiles("Areas" ,"*.cshtml", SearchOption.AllDirectories);
foreach (var filePath in viewFiles)
{
var pathParas = filePath.Split("\\");
var htmlDoc = new HtmlDocument();
htmlDoc.Load(filePath);
// Get all HTML elements (nodes)
var htmlNodes = htmlDoc.DocumentNode.Descendants()
.Where(node => node.NodeType == HtmlNodeType.Element);
// List all HTML elements
foreach (var node in htmlNodes)
{
var info = new Info();
info.Element = node.Name;
info.Controller = pathParas[pathParas.Length - 2];
info.Area = pathParas[pathParas.Length - 4];
info.View = pathParas[pathParas.Length - 1].Split(".")[0];
foreach (var attribute in node.Attributes)
{
switch (attribute.Name)
{
case "asp-for":info.aspfor = attribute.Value;break;
case "id": info.Id = attribute.Value; break;
case "name": info.Name = attribute.Value; break;
};
}
infos.Add(info);
}
}
return View(infos);
}
Index.cshtml
@model List<Info>
<table class="table">
<thead>
<tr>
<th>Area</th>
<th>Controller</th>
<th>View</th>
<th>Element</th>
<th>asp-for</th>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
@foreach (var info in Model)
{
<tr>
<td>@info.Area</td>
<td>@info.Controller</td>
<td>@info.View</td>
<td>@info.Element</td>
<td>@info.aspfor</td>
<td>@info.Id</td>
<td>@info.Name</td>
</tr>
}
</tbody>
</table>