ViewData 始终为空
ViewData is always null
我知道很多人问过这个问题,但是 none 已经解决了我的问题,请看简单的两个代码片段,我使用的是 dotnet core 2.2。
我在 ViewData
中设置数据的方式有什么问题。
Controller.cs:
public async Task<IActionResult> GetWebTripMetaData(Guid tripId)
{
try
{
ViewData["Greeting"] = "Hello World!";
return View();
}
catch (Exception)
{
return BadRequest("Internal Server Error");
}
}
查看:
@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>
请注意,从视图页面中删除 ViewData["Greeting"]
时效果很好。添加它时,抛出未设置到实例的对象引用。
public IActionResult Index()
{
try
{
ViewData["Greeting"] = "Hello World!";
return View();
}
catch (Exception)
{
return BadRequest("Internal Server Error");
}
}
我只是使用了 ViewBag.Greeting 而不是 ViewData["Greeting"],它工作正常
如果您需要在加载控制器时在 .NET Core 中设置 ViewBag 数据,请重写 OnActionExecuting。在控制器的构造函数中设置时,我的 ViewBag 数据始终为 null。
public override void OnActionExecuting(ActionExecutingContext context)
{
base.OnActionExecuting(context);
this.ViewBag.FullAccountName = $"{this.CurrentLdapUser.DisplayName} ({this.CurrentLdapUser.UserNameWithDomain})";
}
我知道很多人问过这个问题,但是 none 已经解决了我的问题,请看简单的两个代码片段,我使用的是 dotnet core 2.2。
我在 ViewData
中设置数据的方式有什么问题。
Controller.cs:
public async Task<IActionResult> GetWebTripMetaData(Guid tripId)
{
try
{
ViewData["Greeting"] = "Hello World!";
return View();
}
catch (Exception)
{
return BadRequest("Internal Server Error");
}
}
查看:
@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>
请注意,从视图页面中删除 ViewData["Greeting"]
时效果很好。添加它时,抛出未设置到实例的对象引用。
public IActionResult Index()
{
try
{
ViewData["Greeting"] = "Hello World!";
return View();
}
catch (Exception)
{
return BadRequest("Internal Server Error");
}
}
我只是使用了 ViewBag.Greeting 而不是 ViewData["Greeting"],它工作正常
如果您需要在加载控制器时在 .NET Core 中设置 ViewBag 数据,请重写 OnActionExecuting。在控制器的构造函数中设置时,我的 ViewBag 数据始终为 null。
public override void OnActionExecuting(ActionExecutingContext context)
{
base.OnActionExecuting(context);
this.ViewBag.FullAccountName = $"{this.CurrentLdapUser.DisplayName} ({this.CurrentLdapUser.UserNameWithDomain})";
}