Reputation: 1705
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.
Upvotes: 6
Views: 13361
Reputation: 11
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.
Upvotes: 0
Reputation: 3625
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})";
}
Upvotes: 1
Reputation: 1705
I simply used ViewBag.Greeting instead of ViewData["Greeting"] and it worked fine
Upvotes: 9
Reputation: 5
public IActionResult Index()
{
try
{
ViewData["Greeting"] = "Hello World!";
return View();
}
catch (Exception)
{
return BadRequest("Internal Server Error");
}
}
Upvotes: -4