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.
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.
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.
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.
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.
I simply used ViewBag.Greeting instead of ViewData["Greeting"] and it worked fine
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With