Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 840
Mohamad Mousheimish Avatar asked Feb 25 '19 13:02

Mohamad Mousheimish


People also ask

Can ViewData be null?

ViewData is used to pass data from controller to corresponding view. Its life lies only during the current request. If redirection occurs then its value becomes null.

What kind of object is ViewData?

ViewBag, ViewData, and TempData all are Dictionary objects in ASP.NET MVC and these are used for data passing in various situations. The following are the situations where we can use TempData and other objects. Pass the data from Controller to View.

Which is better ViewBag or ViewData?

ViewData and ViewBag are used for the same purpose -- to transfer data from controller to view. ViewData is nothing but a dictionary of objects and it is accessible by string as key. ViewData is a property of controller that exposes an instance of the ViewDataDictionary class. ViewBag is very similar to ViewData.

How do you define ViewData?

ViewData is a dictionary of objects that are stored and retrieved using strings as keys. It is used to transfer data from Controller to View. Since ViewData is a dictionary, it contains key-value pairs where each key must be a string. ViewData only transfers data from controller to view, not vice-versa.


1 Answers

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

like image 168
Mohamad Mousheimish Avatar answered Sep 29 '22 20:09

Mohamad Mousheimish