ASP.NET PartialView
最后修改于 2025 年 4 月 3 日
在本文中,我们将探讨 ASP.NET 8 中的 PartialView。PartialView 是在 ASP.NET MVC 应用程序中创建可重用 UI 组件的强大功能。
ASP.NET 是一个跨平台、高性能的框架,用于构建现代 Web 应用程序。PartialView 有助于将复杂的视图分解为更小的组件。
基本定义
ASP.NET 中的 PartialView 是一种特殊的视图,用于渲染部分 HTML 内容。它通常用于将大型视图分解为更小、可重用的组件。
可以使用 Partial 或 PartialAsync HTML 辅助方法在其他视图中渲染 PartialViews。它们支持与常规视图相同的 Razor 语法,但没有布局页。
PartialViews 通常用于导航菜单、页眉、页脚或跨多个页面出现的任何 UI 元素等组件。它们提高了代码的可维护性并减少了重复。
ASP.NET PartialView 示例
以下示例演示了如何在 ASP.NET 8 中创建和使用 PartialView。
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.UseStaticFiles();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
这会设置一个基本的 ASP.NET MVC 应用程序。AddControllersWithViews 方法支持视图的 MVC。添加了静态文件中间件以支持 CSS/JS。
using Microsoft.AspNetCore.Mvc;
public class HomeController : Controller
{
public IActionResult Index()
{
var products = new List<Product>
{
new(1, "Laptop", 999.99m),
new(2, "Mouse", 19.99m),
new(3, "Keyboard", 49.99m)
};
return View(products);
}
public IActionResult ProductTable()
{
var products = new List<Product>
{
new(1, "Laptop", 999.99m),
new(2, "Mouse", 19.99m),
new(3, "Keyboard", 49.99m)
};
return PartialView("_ProductTable", products);
}
}
public record Product(int Id, string Name, decimal Price);
控制器有两个操作。Index 返回带有所有产品的主视图。ProductTable 返回一个仅包含产品表组件的 PartialView。
@model IEnumerable<Product>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
@foreach (var product in Model)
{
<tr>
<td>@product.Id</td>
<td>@product.Name</td>
<td>@product.Price.ToString("C")</td>
</tr>
}
</tbody>
</table>
此 PartialView 定义了一个可重用的产品表组件。它遵循以_开头命名约定。模型是强类型的 IEnumerable<Product>。
@model IEnumerable<Product>
<h1>Product Catalog</h1>
<div class="row">
<div class="col-md-8">
@await Html.PartialAsync("_ProductTable", Model)
</div>
<div class="col-md-4">
<h3>Recently Viewed</h3>
<!-- Other content -->
</div>
</div>
<button id="refreshBtn" class="btn btn-primary">Refresh Table</button>
@section Scripts {
<script>
document.getElementById('refreshBtn').addEventListener('click', async () => {
const response = await fetch('/Home/ProductTable');
const html = await response.text();
document.querySelector('.col-md-8').innerHTML = html;
});
</script>
}
主视图使用 PartialAsync 渲染产品表。JavaScript 演示了通过 AJAX 仅刷新表,展示了 PartialView 在部分页面更新方面的强大功能。
此示例展示了 PartialViews 如何实现基于组件的 UI 开发。该表可以在视图之间重用,并通过 AJAX 调用独立更新。
来源
Microsoft ASP.NET PartialView 文档
在本文中,我们探讨了 ASP.NET 8 中的 PartialView。此强大功能有助于创建模块化、可维护且高效的 Web 应用程序。