.Net Core MVC.
In all my views and partial views, I use this line to get its path (url)
<span>@(this.ViewContext.View as Microsoft.AspNetCore.Mvc.Razor.RazorView).Path;</span>
(and also some other lines to get the models name in case its strongly-typed and some other info)
Now, to avoid having to add this code in every view or partial, I have tried to create a partial (_debugPartial.cshtml) with these lines, and then including it in every other view/partial with
<partial name="_DebugInfoPartial" />
But this does not work: I always get the name of this new partial, ("/Views/Shared/_debugPartialchstml") instead of tha path of the view/partial that is including it...
How could this be achieved?
You could use the custom tag helper to achieve your requirement. The partial view is also a view , which will always use the same view path.
More detail about how to use it, you could refer to below codes:
Create a custom taghelper:
[HtmlTargetElement("debuginfo")]
public class DebugInfoTagHelper : TagHelper
{
[ViewContext]
public ViewContext ViewContext { get; set; }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
var viewPath = (ViewContext.View as RazorView)?.Path;
// Capture any other information you need
output.TagName = "span";
output.Content.SetContent($"View Path: {viewPath}");
// Render other debug information as needed
}
}
Import it inside the _ViewImports.cshtml
.
@using WebApplication1
@namespace WebApplication1.Pages
@addTagHelper *, {yourapplicationnamespace}
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
Usage:
<debuginfo></debuginfo>
Result: