【问题标题】:Casting ViewBag to List<SelectListItem> gives null reference exception将 ViewBag 转换为 List<SelectListItem> 会产生空引用异常
【发布时间】: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


【解决方案1】:

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

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

select option:disabled {
    display:none;
}

asp-items="ViewBag.Programmes

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-15
    • 2018-04-01
    • 2011-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-29
    • 2015-10-29
    相关资源
    最近更新 更多