Search code examples
asp.net-mvcrazorasp.net-core.net-corerazor-pages

ViewData is always null


I know lots of people asked this but none have solved my issue, please look at the simple two code snippets, I'm using dotnet core 2.2.

What's wrong with the way I'm setting the data inside of ViewData.

Controller.cs:

public async Task<IActionResult> GetWebTripMetaData(Guid tripId)
{
    try
    {
        ViewData["Greeting"] = "Hello World!";
        return View();
    }
    catch (Exception)
    {
        return BadRequest("Internal Server Error");
    }
}

View:

@page
@model TripTale.Backend.Pages.tripModel
<html>
  <head>
      <link href="@Url.Content("~/Styles/trip.css")" rel="stylesheet" type="text/css" />
   </head>
    <body>
        @ViewData["Greeting"]
    </body>
</html>

Please note that when removing the ViewData["Greeting"] from view page it work fine. When adding it, Object reference not set to an instance is thrown.


Solution

  • I simply used ViewBag.Greeting instead of ViewData["Greeting"] and it worked fine