ViewData is always null
Asked Answered
H

4

6

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.

Heresy answered 25/2, 2019 at 13:4 Comment(2)
Why are you using ViewData if you are passing a model to the view? Why dont you just use the model?Vesuvius
I know I could do that, but i was just testing a simple thing, and the scenario above occurred so I wanted to know what's happening.Heresy
H
8

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

Heresy answered 26/2, 2019 at 13:46 Comment(0)
H
1

If you are needing to set ViewBag data in .NET Core when your controller loads, override OnActionExecuting. My ViewBag data was always null when setting it in the controller's constructor.

    public override void OnActionExecuting(ActionExecutingContext context)
    {
        base.OnActionExecuting(context);
        this.ViewBag.FullAccountName = $"{this.CurrentLdapUser.DisplayName} ({this.CurrentLdapUser.UserNameWithDomain})";
    }
Haematopoiesis answered 22/9, 2021 at 20:54 Comment(0)
A
0

We had a similar issue. We have changed ViewData to ViewBag.Greeting as Mohamad Mousheimish said. This worked for cases like ViewBag.Greeting.Title = "Title" but on my page I had some elements and model expressions that kept using ViewData. Then we removed the @Page directive and after that everything worked fine.

Ashelyashen answered 3/11, 2022 at 8:26 Comment(0)
B
-4
public IActionResult Index()
{
    try
    {
            ViewData["Greeting"] = "Hello World!";
            return View();
    }
    catch (Exception)
    {
            return BadRequest("Internal Server Error");
    }
}
Bessel answered 26/2, 2019 at 5:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.