将ViewBag强制转换为List <SelectListItem>会给出空引用异常

时间:2019-12-04 03:59:36

标签: c# .net asp.net-mvc asp.net-core asp.net-core-tag-helpers

下面的代码可以按需工作,但是保存表单后,开发人员工具的“网络”标签预览中将存在空引用异常

我想我理解为什么发生异常,并且我尝试了不同的方法来针对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">

1 个答案:

答案 0 :(得分:0)

我认为问题在于Viewbag没有被填充在返回的部分中。

我找到了一个更简单的解决方案,但是使用了一些CSS:

select option:disabled {
    display:none;
}

asp-items="ViewBag.Programmes