RedirectToAction inside a action method that creates a new object in the entity in MVC

Obsivus picture Obsivus · May 10, 2012 · Viewed 7.3k times · Source

I have a action method that is following:

    public ActionResult CreateNKITemplate(int id)
    {
        var goalcard = createNKIRep.GetGoalCardByID(id);
        createNKIRep.CreateTemplate(goalcard);

        return View();
    }

This action method will create a new GoalCard object inside my GoalCard Entity which means it will basicly generate an ID.

Inside CreateTemplate action method I want to remove return View(); and add return RedirectToAction so it redirects to the new GoalCard object id that was created

I want to redirect the new GoalCard object ID to:

public ActionResult Edit(int id)
{
   // code..
}

How can I do this?

Basicly: Copy and create a new Object and then redirect the new object id to this edit action method that takes Id as parameter.

UPDATE:

Accepted Answer solution:

   public ActionResult CreateNKITemplate(int id)
    {
       var goalcard = createNKIRep.GetGoalCardByID(id);
       var copygoalcard = createNKIRep.CreateTemplate(goalcard);
       var GoalCardCopyID = copygoalcard.Id;

       return RedirectToAction(
              "Edit", // Action name
              "CreateNKI", // Controller name
              new { id = GoalCardCopyID }); // Route values

    }

Thanks in advance!

Answer

user672118 picture user672118 · May 10, 2012

Well, the definition for RedirectToAction is.

protected internal RedirectToRouteResult RedirectToAction(
    string actionName,
    string controllerName,
    Object routeValues
)

So we just fill in your values.

RedirectToAction(
    "Edit",                // Action name
    "GoalCardController",  // Controller name
    new { id = gcId }      // Route values
)

Note that the above code assumes that your controller is called GoalCardController and that the id is stored in a variable called gcId.