ASP.NET Core:非Ajax方式在Razor Page获取Syncfusion Grid的count值
解决方案
因为你没有使用Ajax调用,说明后端的FetchData返回的JSON数据是直接传递到Razor Page页面中的(比如通过ViewData、ViewBag或者PageModel属性),你可以通过以下几种方式获取count值:
1. 直接通过PageModel属性访问(推荐)
如果你的PageModel中已经把FetchData返回的完整数据存储为属性:
// PageModel代码 public class YourPageModel : PageModel { // 存储完整的返回数据(包含result和count) public dynamic GridFullData { get; set; } public void OnGet() { // 假设FetchData返回的是包含result和count的匿名对象或强类型对象 GridFullData = FetchData(); } // 你的FetchData方法 private dynamic FetchData() { // 示例数据,实际替换为你的业务逻辑 var dataList = new List<object>(); var totalCount = 120; return new { result = dataList, count = totalCount }; } }
在Razor Page页面中,直接通过Model访问count:
<!-- 绑定Grid的result数据 --> <ejs-grid DataSource="@Model.GridFullData.result"> <!-- 你的Grid列配置 --> <e-columns> <e-column Field="xxx" HeaderText="xxx"></e-column> <!-- 其他列 --> </e-columns> </ejs-grid> <!-- 显示count值 --> <p>总记录数: @Model.GridFullData.count</p>
2. 通过ViewData/ViewBag传递数据
如果是用ViewData传递完整的JSON数据对象:
// PageModel代码 public void OnGet() { var fullData = FetchData(); ViewData["GridFullData"] = fullData; }
页面中转换为动态类型后访问:
@{ var gridFullData = ViewData["GridFullData"] as dynamic; } <ejs-grid DataSource="@gridFullData.result"> <!-- 列配置 --> </ejs-grid> <p>总记录数: @gridFullData.count</p>
3. 处理JSON字符串(如果FetchData返回的是字符串格式的JSON)
如果FetchData返回的是纯JSON字符串(而非对象),需要先反序列化:
// PageModel代码 public void OnGet() { string jsonStr = FetchData(); // 返回格式为 {"result": [...], "count": 100} 的字符串 ViewData["GridJson"] = jsonStr; }
页面中解析JSON获取count:
@{ using System.Text.Json; var jsonDocument = JsonDocument.Parse(ViewData["GridJson"].ToString()); // 获取count值 int totalCount = jsonDocument.RootElement.GetProperty("count").GetInt32(); // 解析result数据给Grid绑定 var gridDataSource = jsonDocument.RootElement.GetProperty("result").Deserialize<IEnumerable<dynamic>>(); } <ejs-grid DataSource="@gridDataSource"> <!-- 列配置 --> </ejs-grid> <p>总记录数: @totalCount</p>
核心思路就是:既然Grid已经能绑定result,说明你已经拿到了完整的JSON数据(无论是对象还是字符串),只需要在绑定Grid的同时,直接从完整数据中提取count属性即可,不需要额外的请求。
内容的提问来源于stack exchange,提问作者topcool
相关产品推荐
相关产品推荐

