英文:
ASP.Net Core lifecycle of ViewBag
问题
我正在将一个传统的ASP.Net MVC网站转换为Core,我过去常常让所有的控制器都继承自一个BaseController类,该类覆盖了Initialize
方法,并在ViewBag
上设置了一些属性。现在似乎没有Initialize
方法了,所以我通过构造函数来做这个。然而,当我到达操作方法时,似乎ViewBag
已经被重置了。
代码基本上是这样的:
public abstract class BaseController : Controller
{
protected BaseController()
{
ViewBag.Hello = "hello";
}
}
public class MyController : BaseController
{
public IActionResult Index()
{
var hello = ViewBag.Hello;
// 但hello是null
return View();
}
}
我应该覆盖一个不同的方法,而不是通过构造函数吗?ViewBag
在哪里被重置,有没有更好的方法来解决这个问题?
您可以尝试使用ASP.NET Core中的OnActionExecuting
方法来设置ViewBag
属性,而不是通过构造函数。这可以确保在执行操作之前设置ViewBag
属性,而不会被重置。
以下是修改后的示例代码:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
public abstract class BaseController : Controller
{
public override void OnActionExecuting(ActionExecutingContext context)
{
base.OnActionExecuting(context);
ViewBag.Hello = "hello";
}
}
public class MyController : BaseController
{
public IActionResult Index()
{
var hello = ViewBag.Hello;
// 现在hello应该包含"hello"的值
return View();
}
}
通过覆盖OnActionExecuting
方法,您可以确保在执行操作之前设置ViewBag
属性,从而避免被重置。这是在ASP.NET Core中更常见的一种方式来处理此类情况。
英文:
I am converting a legacy ASP.Net MVC website to Core, and I used to have all controllers inherit from a BaseController class which was overriding Initialize
and setting some properties on the ViewBag
. There seems to be no Initialize
method now, so I'm doing that through the constructor. However, by the time I get to the Action method, it seems the ViewBag
has been reset.
The code is basically like this:
public abstract class BaseController : Controller
{
protected BaseController()
{
ViewBag.Hello = "hello";
}
}
public class MyController : BaseController
{
public IActionResult Index()
{
var hello = ViewBag.Hello;
// but hello is null
return View();
}
}
Should I be overriding a different method rather than going through the constructor? Where is ViewBag
getting reset and what is a better way to work around that?
答案1
得分: 0
尝试重写 OnActionExecuting 方法:
public abstract class BaseController : Controller
{
//protected BaseController()
//{
// ViewBag.Hello = "hello";
//}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
ViewBag.Hello = "hello"
base.OnActionExecuting(filterContext);
}
}
结果:
英文:
Try to override OnActionExecuting method :
public abstract class BaseController : Controller
{
//protected BaseController()
//{
// ViewBag.Hello = "hello";
//}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
ViewBag.Hello = "hello";
base.OnActionExecuting(filterContext);
}
}
result:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论