ASP.NET Core Razor Page如何传递选中名称到另一列表页过滤数据
问题原因
你代码的核心问题是后台拿到路由传递的name参数后没有对查询结果进行过滤,直接返回了全量表数据,其次还存在空数据场景下的空引用风险,按以下步骤修改即可:
第一步:修改后台DataModel代码
增加过滤逻辑,同时新增属性存储当前查询的表名,避免前端空引用:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; using EpicorDevInfo.Data; using EpicorDevInfo.Models; namespace EpicorDevInfo.Pages.UDTables.Data { public class DataModel : PageModel { private readonly EpicorDevInfoContext _context; public DataModel(EpicorDevInfoContext context) { _context = context; } public IList<UDTableData> UDTableData { get; set; } // 新增属性存储当前查询的表名 public string CurrentTableName { get; set; } public async Task<IActionResult> OnGetAsync(string name) { if (String.IsNullOrEmpty(name)) { return NotFound(); } CurrentTableName = name; // 增加过滤条件,只查询对应表名的数据 UDTableData = await _context.Epi_UDTableData_TEMP .Where(d => d.TableName == name) .ToListAsync(); // 空结果也正常返回页面,不要返回404 return Page(); } } }
第二步:修改第二个页面的前端代码
替换原有直接取列表首个元素的写法,避免空数据报错:
@page "{name:string}" @model EpicorDevInfo.Pages.UDTables.Data.IndexModel @{ ViewData["Title"] = Model.CurrentTableName; } <h1>@Model.CurrentTableName</h1> <p> <a asp-page="Create">Create New</a></p> <table class="table"> <thead> <tr> <th> @Html.DisplayNameFor(model => model.UDTableData[0].TableName) </th> <th> @Html.DisplayNameFor(model => model.UDTableData[0].ColumnLabel) </th> <th> @Html.DisplayNameFor(model => model.UDTableData[0].DatabaseColumn) </th> <th></th> </tr> </thead> <tbody> @* 加判断,无数据时显示提示 *@ @if (!Model.UDTableData.Any()) { <tr><td colspan="4">暂无该表的字段数据</td></tr> } else { @foreach (var item in Model.UDTableData) { <tr> <td> @Html.DisplayFor(modelItem => item.TableName) </td> <td> @Html.DisplayFor(modelItem => item.ColumnLabel) </td> <td> @Html.DisplayFor(modelItem => item.DatabaseColumn) </td> <td> <a asp-page="./Edit" asp-route-id="@item.ID">Edit</a> | <a asp-page="./Details" asp-route-id="@item.ID">Details</a> | <a asp-page="./Delete" asp-route-id="@item.ID">Delete</a> </td> </tr> } } </tbody> </table>
可选优化(路由跳转异常时使用)
如果跳转时出现404,说明相对路径匹配错误,把第一个页面的跳转链接修改为绝对路径:
<a asp-page="/UDTables/Data/Data" asp-route-name="@item.TableName">@Html.DisplayFor(modelItem => item.TableName)</a>
内容的提问来源于stack exchange,提问作者Shawn Leenerts
相关产品推荐
相关产品推荐

