简体   繁体   中英

Casting ViewBag to List<SelectListItem> gives null reference exception

The code below works as desired but when the form is saved, there is a null reference exception in the network tab preview in the developer tools

I think I understand why the exception is happening and I've tried different approaches to validate against the null for the ViewBag but I keep getting the same error.

Please can someone advise the correct way to perform the cast and validation

<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">

I think the issue was the Viewbag wasn't being populated in the partial that is being returned.

I found a simpler solution however using some css:

select option:disabled {
    display:none;
}

asp-items="ViewBag.Programmes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM