【发布时间】:2019-12-04 03:59:36
【问题描述】:
下面的代码可以正常工作,但是保存表单时,开发者工具的网络标签预览中出现空引用异常
我想我理解为什么会发生异常,并且我尝试了不同的方法来验证 ViewBag 的 null,但我一直收到相同的错误。
请有人建议执行转换和验证的正确方法
<select asp-for="Pathways" id="pathwaysDropdown"
asp-items="((List<SelectListItem>)ViewBag.Programmes).Where(a => a.Disabled == false)">
</select>
//The below are some things I've tried but don't work, but hopefully will show what I'm trying to achieve:
asp-items="(ViewBag.Programmes ? new List<SelectListItem>() :
(List<SelectListItem>)ViewBag.Programmes).Where(a => a.Disabled == false)">
asp-items="((List<SelectListItem>)ViewBag.Programmes ??
new List<SelectListItem>()).Where(a => a.Disabled == false)">
//Error
ArgumentNullException: Value cannot be null. Parameter name: source
System.Linq.Enumerable.Where<TSource>(IEnumerable<TSource> source, Func<TSource, bool> predicate)
AspNetCore.Views_Marketing_Partials__OverviewFields.<ExecuteAsync>b__70_2() in _OverviewFields.cshtml
+
<td>
<div id="pathwaysList" class="initiallyHidden paddingbot paddingtop">
<select asp-for="Pathways" id="pathwaysDropdown"
asp-items="((List<SelectListItem>)ViewBag.Programmes).Where(a => a.Disabled == false)">
<option value="" disabled hidden>----</option>@*selected*@
</select>
<input type="hidden" asp-for="PathwaysOfProgramme" />
</div>
<table id="pathwaysTable" class="table">
<tr id="pathwayHeaders">
【问题讨论】:
-
您必须提供更多信息。您尝试过的代码是什么,遇到的错误是什么?
-
显示你的控制器的代码
-
您可以检查您的 ViewBag 是否为空:
@if(ViewBag.Programmes !=null){//do your work} else {//handle exception on your View}
标签: c# .net asp.net-mvc asp.net-core asp.net-core-tag-helpers