ASP.NET Core中如何以更优雅的方式在Razor视图中嵌入其他视图
Hey there! Let's break this down for you:
In traditional ASP.NET Core Razor views (the .cshtml files used in MVC or Razor Pages), there isn't native support for that super clean Blazor-style <MyView /> syntax to embed partial views right out of the box. But don't worry—we've got two solid ways to get a more concise experience, even mimicking that Blazor feel if you want:
1. Simplify with PartialAsync
If you don't need direct streaming output (the key difference between RenderPartialAsync which writes directly to the response stream, and PartialAsync which returns an IHtmlContent), you can trim down your code to a single line without wrapping it in a code block:
@await Html.PartialAsync("MyView", Model)
This is way cleaner than the original @{await Html.RenderPartialAsync(...);} and is one of the go-to recommended approaches from Microsoft for partial views.
2. Build a Custom Tag Helper for Blazor-Like Syntax
If you really want that <MyView />-style simplicity, you can create a custom tag helper to replicate it. Here's how:
Step 1: Create the Tag Helper Class
Add a new class to your project (e.g., PartialViewTagHelper.cs) with this code:
using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.AspNetCore.Razor.TagHelpers; [HtmlTargetElement("partial-view", Attributes = "name, model")] public class PartialViewTagHelper : TagHelper { private readonly IHtmlHelper _htmlHelper; public PartialViewTagHelper(IHtmlHelper htmlHelper) { _htmlHelper = htmlHelper; } [HtmlAttributeName("name")] public string ViewName { get; set; } [HtmlAttributeName("model")] public object Model { get; set; } [ViewContext] [HtmlAttributeNotBound] public ViewContext ViewContext { get; set; } public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { // Wire up the HtmlHelper with the current view context (_htmlHelper as IViewContextAware)?.Contextualize(ViewContext); // Render the partial view var partialContent = await _htmlHelper.PartialAsync(ViewName, Model); // Replace the tag with the partial view content and remove the original tag output.Content.SetHtmlContent(partialContent); output.TagName = null; } }
Step 2: Register the Tag Helper
Open your _ViewImports.cshtml file and add a reference to your tag helper's namespace (replace YourProjectNamespace with the actual namespace where your tag helper lives):
@addTagHelper *, YourProjectNamespace
Step 3: Use It in Your Views
Now you can embed your partial view with syntax that's almost identical to Blazor:
<partial-view name="MyView" model="@Model" />
If you don't need to pass a model, you can simplify it even further:
<partial-view name="MyView" />
For extra polish, you could tweak the tag helper to auto-match the tag name to the partial view name (e.g., <my-view> maps to MyView.cshtml), but the above implementation covers most common use cases with minimal fuss.
内容的提问来源于stack exchange,提问作者user11409100

