You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为展示JSON数据的ASP.NET Core Razor表格添加userId搜索功能

解决ASP.NET Core Razor页面按userId筛选JSON数据的问题

你需要在控制器中对获取到的JSON数据做过滤处理,只保留匹配输入userId的条目,不需要用到_context(那是EF Core操作数据库的上下文对象,你这里是内存数据过滤,用不上)。具体修改如下:

1. 修改控制器逻辑

在ToDoData控制器的ToDoModel方法中,获取反序列化后的列表后添加过滤逻辑:

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using ToDo.Models;
using System.Net;

namespace ToDo.Controllers
{
    public class ToDoData : Controller
    {
        public ActionResult ToDoModel(string searchString)
        {
            ViewData["CurrentFilter"] = searchString;
            var webClient = new WebClient();
            webClient.Headers.Add(HttpRequestHeader.Cookie, "cookievalue");
            var json = webClient.DownloadString(@"https://jsonplaceholder.typicode.com/todos");
            var _toDoData = JsonConvert.DeserializeObject<List<ToDoStructure>>(json);

            // 新增过滤逻辑
            if (!string.IsNullOrEmpty(searchString) && int.TryParse(searchString, out int userId))
            {
                _toDoData = _toDoData.Where(t => t.userId == userId).ToList();
            }

            return View(_toDoData);
        }
    }
}

逻辑说明:

  • 先判断搜索字符串非空,同时尝试将其转为整数(因为userId是int类型)
  • 转换成功后,用LINQ的Where方法筛选出userId匹配的条目,再转回List传给视图

2. 视图优化(可选)

给搜索输入框设置type="number",避免用户输入非数字内容:

Find by userId: <input type="number" name="SearchString" value="@ViewData["CurrentFilter"]" />

关于_context的说明

你看到的_context是Entity Framework Core的数据库上下文对象,用于连接、操作关系型数据库(比如从SQL Server读取数据)。而你当前是直接从外部接口获取JSON数据并在内存中处理,完全不需要用到_context,直接对内存中的List<ToDoStructure>做LINQ过滤即可。

内容的提问来源于stack exchange,提问作者Kerkus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 20:45:57