Razor Pages实现按输入值查询Employee表遇ArgumentNullException问题求助
错误排查与修复方案
错误根源分析
出现ArgumentNullException: Value cannot be null. (Parameter 'source')的核心原因是集合为null时调用了Linq扩展方法,具体场景:
- 页面初始加载时,若
_context.Employees为null,Model.Employee保持null,渲染_DisplaySearchPartial视图时,Model.Count()会触发异常(Count()的source参数为null)。 - 搜索请求处理时,未判断
_context.Employees是否为null,直接调用Where方法,同样会触发该异常。 - 额外问题:业务逻辑与需求不符(需求按
DepartmentID筛选,但代码用了EmployeeId)、模型缺少DepartmentID字段、AJAX验证token选择器语法错误。
具体修复步骤
1. 修正Employee模型(添加DepartmentID字段)
根据需求,模型需新增DepartmentID字段,同时补全PhotoFileName的非空声明:
using System; using System.ComponentModel.DataAnnotations; namespace PracticeApp.Models { public partial class Employee { [Key] public int EmployeeId { get; set; } public string EmployeeName { get; set; } = null!; public int DepartmentID { get; set; } // 新增需求所需字段 public string Department { get; set; } = null!; public DateTime DateofJoining { get; set; } public string PhotoFileName { get; set; } = null!; // 补全非空声明 } }
2. 修正IndexModel的空值处理
确保所有返回给视图的集合不为null,避免Linq方法调用时触发异常:
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; using PracticeApp.Models; namespace PracticeApp.Pages { public class IndexModel : PageModel { private readonly CompanyContext _context; public IList<Employee> Employee { get; set; } = new List<Employee>(); // 初始化空集合 public IndexModel(CompanyContext context) { _context = context; } public async Task OnGetAsync() { if (_context.Employees != null) { Employee = await _context.Employees.ToListAsync(); } // 若_context.Employees为null,保持Employee为空集合 } public ActionResult OnPostSearch(int? value) // 改为可空int,处理空输入 { var result = new List<Employee>(); if (value.HasValue && _context.Employees != null) { // 按需求使用DepartmentID筛选 result = _context.Employees.Where(x => x.DepartmentID == value.Value).ToList(); } return Partial("_DisplaySearchPartial", result); } } }
3. 修正部分视图的空值判断
避免直接在null集合上调用Count(),改用Any()并先判断Model是否为null:
@model IEnumerable<Models.Employee> <p>Search Result</p> @if (Model != null && Model.Any()) { <table> <tr><td>@Html.DisplayNameFor(m => m.EmployeeName)</td></tr> @foreach (Models.Employee item in Model) { <tr><td>@Html.DisplayTextFor(m => item.EmployeeName)</td></tr> } </table> } else { <p>No data</p> }
4. 修正AJAX的验证token选择器
移除input与hidden之间的空格,确保能正确获取请求验证token,同时阻止表单默认提交行为:
@section scripts { <script> $("#search").click(function(e) { e.preventDefault(); // 阻止表单默认提交,避免与AJAX请求冲突 $.ajax({ url: "/Index?handler=Search", type: "POST", data: { value: $("#Entervalue").val() }, headers: { RequestVerificationToken: $('input:hidden[name="__RequestVerificationToken"]').val() }, success: function(data) { $("#result").html(data); } }); }); </script> }
内容的提问来源于stack exchange,提问作者TheGame1083
相关产品推荐
相关产品推荐

