简体   繁体   中英

Return the right parent's `get` after a child `post` action

I have the same child action placed in several parents actions, let's say there are these two parent views :

@model Parent1Model 

@{
ViewBag.Title = "Parent1";
Layout = "~/Views/Shared/_Layout.cshtml";

}
@Html.Action("Child","MainControler")

The second parent :

@model Parent2Model

@{
ViewBag.Title = "Parent2";
Layout = "~/Views/Shared/_Layout.cshtml";

}
@Html.Action("Child","MainControler")

All actions are placed in the same controller.

public ActionResult parent1() //GET
{
    Parent1Model model = new Parent1Model()
    return View(model );
}
public ActionResult parent2() //GET
{
    Parent2Model model = new Parent2Model()
    return View(model );
}
public ActionResult Child() //GET
{
    ChildModel model = new ChildModel()
    return View(model );
}

[HttpPost]
public ActionResult Child(ChildModel model) //POST
{
    DoThingsWithResult(model)

    // The next line should return the get of the parent action

    return RedirectToParent() // This does not exist...
}

Now, how do i tell the child to call his RIGHT parent's GET ? Being the child of many parents, how can he know which parent called it this time ?

I could not find anything, neither on google nor in the "Questions that may already have your answer".

You can add one more param to determine where it is coming from, you can also make this param a string which will be the parent action name itself and pass that param to your RedirectToAction(param)

Ex

[HttpPost]
public ActionResult Child(string ParentName, ChildModel model) //POST
{
    DoThingsWithResult(model)

    // The next line should return the get of the parent action

    return RedirectToAction(ParentName) // This does not exist...
}

in your parent action

public ActionResult parent2() //GET
{
    Parent2Model model = new Parent2Model();
    ViewBag.Parent = "parent2";
    return View(model );
}

in your view

@model Parent2Model

@{
ViewBag.Title = "Parent2";
Layout = "~/Views/Shared/_Layout.cshtml";

}
@Html.Action("Child","MainControler", new {ParentName= ViewBag.Parent})

Do the same for Parent Action 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM