-1

Tried a lot of suggestions available on internet but almost all ends up with the same error. Any help would be appreciated, thank you. I am new and learning, please excuse if this elementary level question. Why I am not able to access ViewData in my view?

Controller

public ActionResult BroadcastData()
{
    List<Broadcast> BroadcastList = new List<Broadcast>();
    BroadcastList = (from d in _db.Boradcast
                    select d).ToList();            

    ViewData["BroadcastData"] = BroadcastList;

    return View(BroadcastList);
}

View

@model List<SideCar.Models.Broadcast>

@{
    var viewDataMyObj = ViewData["BroadcastData"] as List<SideCar.Models.Broadcast>;
}

@foreach (var item in viewDataMyObj.ToList())
{
    <h2>@item.BroadcastHeading</h2>
}

Following error occurs:

ArgumentNullException: Value cannot be null. (Parameter 'source') System.Linq.ThrowHelper.ThrowArgumentNullException(ExceptionArgument argument)

If I remove .ToList() from view after viewDataMyObj.ToList() within @foreach then I receive following:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

Jackdaw
  • 7,626
  • 5
  • 15
  • 33
dataENQ
  • 29
  • 4
  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Ian Kemp Jan 13 '21 at 21:56

1 Answers1

0

It seems the BroadcastList doesn't have any data. Put a break point on the last line of your method and check that list.