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

.NET Core表格与下拉框绑定提交时出现对象引用错误

问题排查与解决方案

核心问题分析

你遇到的Object reference not set to an instance of an object.空引用错误,主要源于表单字段与模型属性绑定不匹配,以及Post方法中ViewModel未正确初始化两个关键点:

  1. 视图中下拉框的命名无法被模型绑定器识别,导致提交后HREmployeeRelationVM的核心属性未被正确赋值;
  2. 若Post方法需要返回视图,未重新加载EmployeeList等数据,导致视图渲染时访问null属性报错。

具体修复步骤

1. 修正视图的表单绑定逻辑

将下拉框改为强类型绑定,并添加隐藏字段回传员工基础数据(表单仅提交表单控件的值,显示文本不会自动回传):

@model handbook.ViewModel.HREmployeeRelationVM

@{
    ViewData["Title"] = "Index";
}

@using (Html.BeginForm("Index", "AssignToHr", FormMethod.Post))
{
    <div class="table-reponsive box">
        <table id="example" class="table table-striped table-bordered">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Employee Name</th>
                    <th>Location</th>
                    <th>Department</th>
                </tr>
            </thead>
            <tbody>
                @for (var i = 0; i < Model.EmployeeList.Count(); i++)
                {
                    <tr>
                        <td>@Model.EmployeeList[i].CanditateId</td>
                        @* 添加隐藏字段回传员工ID、姓名、邮箱 *@
                        @Html.HiddenFor(m => m.EmployeeList[i].CanditateId)
                        @Html.HiddenFor(m => m.EmployeeList[i].CanditateName)
                        @Html.HiddenFor(m => m.EmployeeList[i].CanditateEmail)
                        
                        <td>@Model.EmployeeList[i].CanditateName</td>
                        <td>@Model.EmployeeList[i].CanditateEmail</td>
                        @* 强类型绑定到HREmpRelation的hrid属性 *@
                        <td>@Html.DropDownListFor(m => m.EmployeeList[i].hrid, Model.EmployeeList[i].UserList)</td>
                    </tr>
                }
            </tbody>
        </table>
        <input type="submit" value="Submit" /><br />
    </div>
}

2. 完善Post方法的逻辑

Post方法中需先处理提交的数据,若需要返回视图,必须重新初始化EmployeeList并恢复用户之前的选择:

public IActionResult Index()
{
    // 原Get方法逻辑保持不变
    HREmployeeRelationVM her = new HREmployeeRelationVM();
    her.EmployeeList = new List<HREmpRelation>();
    List<SelectListItem> usermaster = new List<SelectListItem>();
    var users = _context.Usermasters;
    usermaster.Add(new SelectListItem
    {
        Text = "Select HR",
        Value = "0"
    });
    foreach (var usr in users)
    {
        usermaster.Add(new SelectListItem
        {
            Text = usr.UserName,
            Value = Convert.ToString(usr.Id)
        });
    }
    var canditatelist = _context.EmployeeBasicInformations;
    foreach (var item in canditatelist)
    {
        her.EmployeeList.Add(new HREmpRelation
        {
            CanditateName = item.EmployeeFirstName + " " + item.EmployeeLastName,
            CanditateId = item.EmployeeId,
            CanditateEmail = item.EmployeeEmail,
            UserList = usermaster
        });
    }
    return View(her);
}

[HttpPost]
public IActionResult Index(HREmployeeRelationVM hREmployeeRelationVM)
{
    // 1. 处理提交的数据(例如保存到数据库)
    if (hREmployeeRelationVM.EmployeeList != null)
    {
        foreach (var emp in hREmployeeRelationVM.EmployeeList)
        {
            // 这里可以获取emp.CanditateId(员工ID)和emp.hrid(选中的HR ID),执行保存逻辑
            // 示例:_context.HREmployeeRelations.Add(new ...);
        }
        _context.SaveChanges();
    }

    // 2. 重新初始化ViewModel,用于返回视图(若不需要返回视图可直接跳转)
    hREmployeeRelationVM.EmployeeList = new List<HREmpRelation>();
    List<SelectListItem> usermaster = new List<SelectListItem>();
    var users = _context.Usermasters;
    usermaster.Add(new SelectListItem
    {
        Text = "Select HR",
        Value = "0"
    });
    foreach (var usr in users)
    {
        usermaster.Add(new SelectListItem
        {
            Text = usr.UserName,
            Value = Convert.ToString(usr.Id)
        });
    }
    var canditatelist = _context.EmployeeBasicInformations;
    foreach (var item in canditatelist)
    {
        // 恢复用户之前的选择
        var selectedHrid = hREmployeeRelationVM.EmployeeList?.FirstOrDefault(e => e.CanditateId == item.EmployeeId)?.hrid ?? "0";
        hREmployeeRelationVM.EmployeeList.Add(new HREmpRelation
        {
            CanditateName = item.EmployeeFirstName + " " + item.EmployeeLastName,
            CanditateId = item.EmployeeId,
            CanditateEmail = item.EmployeeEmail,
            UserList = usermaster,
            hrid = selectedHrid
        });
    }

    return View(hREmployeeRelationVM);
}

3. 模型层的小优化

确保HREmployeeRelationVM的EmployeeList默认初始化,避免空引用:

public class HREmployeeRelationVM
{
    public int[] HRID { get; set; }
    // 初始化List,避免默认null
    public List<HREmpRelation> EmployeeList { get; set; } = new List<HREmpRelation>();
}

public class HREmpRelation
{
    public int CanditateId { get; set; }
    public string CanditateName { get; set; }
    public string CanditateEmail { get; set; }
    public string hrid { get; set; }
    public List<SelectListItem> UserList { get; set; }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 17:12:54