子动作是否与其“父动作”共享相同的 ViewBag?行动?
我对此感到困惑: 我有一个操作,比如说父级,在相应的视图文件中,我调用了一个子操作,比如说子级,父级和子级操作都在同一个控制器中。
我需要子操作和父操作来共享 ViewBag 中的一些数据。现在,我应该做什么?这是我的问题:
当我在父视图文件中调用子操作时,我将 viewbag 传递给它,如下所示: @Html.Action(ViewBag)。 在我的孩子行动中,我这样做:
public PartialViewResult Child(Object ViewBag)
{
//using the data in ViewBag
}
这是正确的方式吗? viewbag 对象是通过引用传递的还是与原始 viewbag 不同的对象(需要更多内存)?
或者,如果子操作默认与其调用父操作共享视图包?
从 Darin Dimitrov 的回答中,我知道我不能做这样的事情:@Html.Action(ViewBag)
但我真的需要传递子动作多参数,我能做什么?
I am confused with this:
I have an action ,say Parent ,and in the corresponding view file ,I have called a child action ,say Child ,both Parent and Child actions are in the same controller.
and I need the Child action and the Parent action to share some data in the ViewBag.Now ,what I should do ?Here is my question:
when I call the Child action in parent's view file ,I pass the viewbag to it like this:
@Html.Action(ViewBag).
in my child action ,I do this:
public PartialViewResult Child(Object ViewBag)
{
//using the data in ViewBag
}
Is this the right way ? Does the viewbag object passed by reference or it is a different object then the original viewbag(more memory needed)?
Or if the Child action is sharing the viewbag with its calling parent Action by default?
From Darin Dimitrov's answer ,I knew that I can't do something like this:@Html.Action(ViewBag)
But I really need to pass the child action muti-parameters,what can I do ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
子操作遵循与父操作不同的控制器/模型/视图生命周期。因此,他们不共享 ViewData/ViewBag。如果您想将参数从父操作传递给子操作,您可以执行以下操作:
并在子操作中:
Child actions follow a different controller/model/view lifecycle than parent actions. As a result they do not share ViewData/ViewBag. If you want to pass parameters to a child action from the parent you could do this:
and in the child action:
有一种方法,但您必须创建一个自定义抽象类作为剃刀视图的基类。然后将父级操作所需的任何内容公开给子级操作。
这就是我在继承自 WebViewPage 的类中获取根控制器的 ViewBag 的方法
There is a way, but you have to create a custom abstract class as the base class for your razor views. Then expose whatever you need to from parent to child actions.
This is how I get the root controller's ViewBag inside a class inheriting from WebViewPage