ASP.NET Core 在Controller的构造函数中设置ViewBag无效,NullReferenceException: Object reference not set to an in

本文记录了一次ASP.NET MVC应用中视图错误的排查过程,错误源于MultiSelectList构造函数参数设置不当,最终通过仔细检查代码发现了问题所在。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

向上错误提示

{"success":false,"code":500,"count":0,"data":null,"msg":"System.NullReferenceException:
 Object reference not set to an instance of an object.\r\n  
 at Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList.GetListItemsWithValueField()\r\n 
 at Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList.GetListItems()\r\n  
 at Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList.GetEnumerator()\r\n   
 at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)\r\n  
 at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)\r\n   
 at Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultHtmlGenerator.GenerateGroupsAndOptions(String optionLabel, IEnumerable`1 selectList, ICollection`1 currentValues)\r\n 
 at Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultHtmlGenerator.GenerateGroupsAndOptions(String optionLabel, IEnumerable`1 selectList)\r\n 
 at Microsoft.AspNetCore.Mvc.TagHelpers.SelectTagHelper.Process(TagHelperContext context, TagHelperOutput output)\r\n   
 at Microsoft.AspNetCore.Razor.TagHelpers.TagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output)\r\n 
 at Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.RunAsync(TagHelperExecutionContext executionContext)\r\n 
 at AspNetCore.Areas_Manager_Views_Brand_Add.<ExecuteAsync>b__24_1() in E:\\*****\\Dis.WebAdmin\\Dis.WebAdmin\\Areas\\Manager\\Views\\Brand\\Add.cshtml:line 51\r\n 
 at Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.GetChildContentAsync(Boolean useCachedResult, HtmlEncoder encoder)\r\n  
 at Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output)\r\n
 at Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.<RunAsync>g__Awaited|0_0(Task task, TagHelperExecutionContext executionContext, Int32 i, Int32 count)\r\n  
 at AspNetCore.Areas_Manager_Views_Brand_Add.ExecuteAsync() in E:\\****\\Dis.WebAdmin\\Dis.WebAdmin\\Areas\\Manager\\Views\\Brand\\Add.cshtml:line 3\r\n  
 at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)\r\n  
 at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, Boolean invokeViewStarts)\r\n 
 at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)\r\n  
 at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, String contentType, Nullable`1 statusCode)\r\n
 at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, String contentType, Nullable`1 statusCode)\r\n  
 at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ActionContext actionContext, IView view, ViewDataDictionary viewData, ITempDataDictionary tempData, String contentType, Nullable`1 statusCode)\r\n   at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext context, ViewResult result)\r\n  
 at Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext context)\r\n  
 at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\r\n   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)\r\n   
 at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)\r\n 
 at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n 
 at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\r\n   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)\r\n   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)\r\n  
 at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
 at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)\r\n  
 at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)\r\n  
 at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)\r\n  
 at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)\r\n 
 at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)\r\n
 at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)\r\n   
 at Dis.Components.ExceptionMiddleware.Invoke(HttpContext context) in E:\\***\\Dis.WebAdmin\\Dis.Components\\Exception\\ExceptionMiddleware.cs:line 38"}

报第3行和第51行错误

看下文件

@{
    ViewData["Title"] = "添加品牌";
    Layout = "~/Areas/Manager/Views/Shared/_Layout.cshtml";
}

第三行提示的是ViewData

    <div class="layui-form-item">
            <label class="layui-form-label">*****/label>
            <div class="layui-input-inline" style="width: 200px;">
                <select name="Supervisor" asp-items="@ViewBag.SupervisorList" lay-filter="Supervisor" lay-search>
                    <option value="">请选择</option>
                </select>
            </div>
        </div>

第51行 显示的是这个ViewBag 

 

开始百度了,我一度怀疑我的viewbag因为数据是null出现了问题,但是为啥其他的是null没问题,

然后考虑要把这个viewbag改成ViewData 

失败,跟本不允许这么写,因为类型就错误了,编译错误。

开始进行后台查询数据的数据对比,

 /// <summary>
        /// 视图
        /// </summary>
        /// <returns></returns>
        public IActionResult Add()
        {
            //
            List<Dis.Entity.RiderMaster> list = _rider.GetList();
            //训练督导
            List<Dis.Entity.RiderMaster> SupervisorList = list.FindAll(s => s.Position == "P03");
            //
            List<Dis.Entity.RiderMaster> OperationsDirectorList = list.FindAll(s => s.Position == "P04");
            //
            List<Dis.Entity.RiderMaster> GeneralManagerList = list.FindAll(s => s.Position == "P05");

            //
            ViewBag.CompanyList = new MultiSelectList(_organization.GetCompany(Client,"1"), "Id", "Name");

            ViewBag.SupervisorList = new MultiSelectList(SupervisorList, "IRiderIdD", "RederName");
            ViewBag.OperationsDirectorList = new MultiSelectList(OperationsDirectorList, "RiderId", "RederName");
            ViewBag.GeneralManagerList = new MultiSelectList(GeneralManagerList, "RiderId", "RederName");
            return View();
        }

感觉没啥问题,继续百度,

结果无意间发现,

 ViewBag.SupervisorList = new MultiSelectList(SupervisorList, "IRiderIdD", "RederName");

看到没 ,这个地方多了一个D ,可能是无意间按到了键盘搞错了,

问题解决了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

开发小能手-roy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值