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

ASP.NET Core MVC修改实体触发NullReferenceException问题求助

问题根本原因

ASP.NET Core 的默认模型绑定器只会对类的公共可读写属性执行绑定,不会绑定公共字段。你的 ModifyInputFormViewModel 中的 InputFormViewModel 定义为公共字段,没有get/set访问器,导致模型绑定器无法识别并赋值,最终整个参数绑定为null。


解决方案

  1. 修改 ModifyInputFormViewModel 定义,将字段改为属性:
public class ModifyInputFormViewModel
{
    // 新增 { get; set; } 改为公共属性
    public InputFormViewModel InputFormViewModel { get; set; }
    public SelectList SolarPanelTypesList { get; set; }
}
  1. 可选检查:确认 InputForm 实体类中所有需要绑定的字段(ID、SolarPanelTypeID、MonthlyElectricityBill、TetoTipusID等)均为公共属性,而非公共字段。
  2. 可选适配:如果POST请求验证失败需要返回视图,请在返回前重新给 ModifyInputFormViewModel 的各类枚举集合、SolarPanelTypesList 赋值,避免视图渲染时出现空引用异常,修改后的POST方法示例:
[HttpPost, ValidateAntiForgeryToken, Authorize]
public async Task<IActionResult> Edit(int id, ModifyInputFormViewModel modifyInputFormViewModel)
{
    if (id != modifyInputFormViewModel.InputFormViewModel.InputForm.ID)
    {
        return NotFound();
    }
    if (ModelState.IsValid)
    {
        await _inputFormService.ModifyInputFormAsync(modifyInputFormViewModel.InputFormViewModel.InputForm);
        return RedirectToAction(nameof(Index));
    }
    // 验证失败,重新填充下拉、单选选项
    modifyInputFormViewModel.InputFormViewModel.TetoTipusEnumerable = await _inputFormService.GetTetoTipusokAsync();
    modifyInputFormViewModel.InputFormViewModel.TetoFedesEnumerable = await _inputFormService.GetTetoFedesekAsync();
    modifyInputFormViewModel.InputFormViewModel.TetoDolesEnumerable = await _inputFormService.GetTetoDolesekAsync();
    modifyInputFormViewModel.InputFormViewModel.NapelemElhelyezesEnumerable = await _inputFormService.GetNapelemElhelyezesekAsync();
    modifyInputFormViewModel.InputFormViewModel.NapelemTipusEnumerable = await _inputFormService.GetNapelemTipusokAsync();
    modifyInputFormViewModel.SolarPanelTypesList = new SelectList(await _solarPanelTypeService.GetSolarPanelTypesAsync(), "ID", "DisplayString");
    return View(modifyInputFormViewModel);
}

补充说明

修改后模型绑定器就能正常解析表单提交的嵌套字段(如InputFormViewModel.InputForm.ID),自动填充到 modifyInputFormViewModel 参数中,不会再出现null的情况。

内容的提问来源于stack exchange,提问作者Mészáros Barnabás

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 06:45:02