Bubinga
Bubinga

Reputation: 703

Passing Data from Controller to Razor Page, error of "Object reference not set to an instance of an object"

I am trying to show some data in my Razor page that I get from my controller, but I'm getting an error of 'Object reference not set to an instance of an object.' Here is how I am getting the data:

public async Task<IActionResult> Timeline(TimelineModel model)
        {    
            model.Timelineinfo = _context.Timelineinfo.FromSqlRaw($"SELECT * FROM `thin-blue-lie`.timelineinfo WHERE Date = '2020-07-07'").ToList();           
            ViewData["Timelineinfo"] = model.Timelineinfo;

            return View("Pages/Timeline.cshtml");
        }

Here is TimelineModel:

public class TimelineModel
    {
        public TimelineModel() {}
        public IList<Timelineinfo> Timelineinfo { get; set; } 
    }

Here is the data it returns: enter image description here I am trying to move that data into my Page by putting the following at the top of my page and accessing it by doing @Event.City for example.

@{
    var Event = ViewData["Timelineinfo"] as ThinBlue.Timelineinfo; 
}

However, I am getting the below error on the var Event line. I get the same error if I dont use ViewData and try to access stuff by doing Model.Timelineinfo[0].City Anybody know how I can fix this?

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

Extra info: When I set a breakpoint at the var Event line, I get this where both sides of the Event equation are null.

Upvotes: 1

Views: 126

Answers (1)

Michael Wang
Michael Wang

Reputation: 4022

You pass List<Timelineinfo> to view in action, but casted as Timelineinfo in Razor page.

var Event = ViewData["Timelineinfo"] as List<ThinBlue.Timelineinfo>;
                                 //not cast as ThinBlue.Timelineinfo

Test codes in controller and Razor page: ![enter image description here ![enter image description here

Screenshots of Test:
enter image description here

In the end, I suggest to change the names to avoid confusion.

public class TimelineModel
{
    public TimelineModel() {}
    public IList<Timelineinfo> Timelineinfos { get; set; } //not Timelineinfo
}

In controller,

ViewData["Timelineinfos"] = model.Timelineinfos;

Upvotes: 1

Related Questions