子动作是否与其“父母"共享相同的 ViewBag?行动? [英] Does a child action share the same ViewBag with its "parents" action?
问题描述
我对此感到困惑:我有一个动作,比如父,在相应的视图文件中,我调用了一个子动作,比如子,父和子动作都在同一个控制器中.
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.
并且我需要 Child 操作和 Parent 操作来共享 ViewBag 中的一些数据.现在,我应该怎么做?这是我的问题:
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:
当我在父视图文件中调用子操作时,我将视图包传递给它,如下所示:@Html.Action(ViewBag).在我的孩子行动中,我这样做:
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
}
这是正确的方法吗?viewbag 对象是通过引用传递的还是与原始 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?
从 Darin Dimitrov 的回答中,我知道我不能做这样的事情:@Html.Action(ViewBag)
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 ?
推荐答案
子操作遵循与父操作不同的控制器/模型/视图生命周期.因此,他们不共享 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:
@Html.Action("Child", new { message = ViewBag.Message })
在子操作中:
public ActionResult Child(string message)
{
...
}
这篇关于子动作是否与其“父母"共享相同的 ViewBag?行动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!