Sergio Romero
Sergio Romero

Reputation: 6607

RedirectToAction does not do what I need. What are my options?

In my controller I have something similar to this:

[HttoPost]
public ActionResult MyMethod(MyViewModel myViewModel)   
{  
   //...Some logic  

   return RedirectToAction("SecondMethod", new { ... pupulating view model ... });  
}   

[HttpGet]
public ActionResult SecondMethod()  
{  
    return RedirectToAction("Index", "SomeOtherController");  
}

[HttpPost]
public ActionResult SecondMethod(MyViewModel myViewModel)  
{  
   //...Do Something
   return View("MyView", myViewModel);  
}

Obviously the RedirectToAction from the MyMethod action will never call the HttpPost one which is what I need. The problem is that if I do the following:

return SecondMethod(myViewModel);

instead, the URL that is displayed on the browser is .../.../.../MyMethod and I need it to be .../.../.../SecondMethod

What can I do so that I can hit the HttpPost action and have the correct URL displayed on the browser?

Thanks for your help.

Upvotes: 2

Views: 870

Answers (3)

Jay
Jay

Reputation: 57969

It sounds like you don't actually need HttpPost; you just need the functionality from that method to be available in a corresponding HttpGet action that accepts an instance of MyViewModel, and returns a view populated by that model. Does that sound right?

If so, try something like this:

[HttpGet]
[ActionName("SecondMethod")]
public ActionResult SecondMethodWithViewModel(MyViewModel myViewModel)
{
    return View("MyView", myViewModel);
}

You can overload your actions by using the ActionNameAttribute, since you can't declare another method with the same signature as your HttpPost action. The RedirectToAction() call and URL will respect the value you set in this attribute, so you can name the method anything you want.

Upvotes: 0

jrummell
jrummell

Reputation: 43097

You can create a non action method and call it from MyMethod() and SecondMethod():

private void DoStuff()
{
    //...Do Something
}

public ActionResult MyMethod(MyViewModel myViewModel)   
{  
   //...Some logic
   DoStuff();  

   return RedirectToAction("SecondMethod", new { ... pupulating view model ... });  
}   

[HttpGet]
public ActionResult SecondMethod()  
{  
    return RedirectToAction("Index", "SomeOtherController");  
}

[HttpPost]
public ActionResult SecondMethod(MyViewModel myViewModel)  
{  
   DoStuff();
   return View("MyView", myViewModel);  
}

Upvotes: 1

Joel Etherton
Joel Etherton

Reputation: 37543

If you want to post to an action you need to POST to that action. My recommendation would be to change the method in which the action is occurring. If it's initiated by a button click, it would be simpler to have multiple forms on your page that post independently or before submitting to use JavaScript to change the action attribute of the form doing the posting.

Upvotes: 0

Related Questions