简体   繁体   中英

How to convert a viewbag which is a list to a SelectList if the viewbag is empty - null?

How do I deal with an empty viewbag that is a list and it can sometimes be empty - a null?

I get the error: "Cannot perform runtime binding on a null reference".

I have an MVC application and passing a viewbag (which is a list) as an argument.

At times it can be empty.

@Html.PagedListPager(Model, page => Url.Action("Index", new { page, movieGenre = (SelectList)ViewBag.movieGenre, searchString = ViewBag.searchString.toString() }))

如果 ViewBag 为空,您可以为其提供默认值。
(Viewbag.something ?? 'This is the value if Viewbag.something is null')

You must first attempt to pull the value from the viewbag and initialize it to an empty SelectList if the value is not there.

Please this code anywhere before the PagedListPager call:

@{
    SelectList movieGenre = (ViewBag.movieGenre == null) ? new SelectList(new List<string>()) : ViewBag.movieGenre;
}

Then use that instance in your rendering call:

@Html.PagedListPager(Model, page => Url.Action("Index", new { page, movieGenre, searchString = ViewBag.searchString.toString() }))

Please note your searchString property might have the same problem.

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