Home > database >  Redirect to an action method of type HttpPost in ASP.NET Core 5 MVC
Redirect to an action method of type HttpPost in ASP.NET Core 5 MVC

Time:11-11

I am working on an ASP.NET Core 5 MVC project and I want to know if it is possible to redirect from an action method to another action method of type post in the same controller.

For example: from the action method I'm working on:

[HttpPost]
public async Task<IActionResult> CurrentWork()
{....}

I want to redirect to another ActionMethod, in the same controller, but of type HttpPost.

The problem is that the action method I want to redirect to also has an HttpGet:

public IActionResult Index()
{...}

[HttpPost]
public async Task<IActionResult> Index(ViewModels models)
{...}

So the redirection I'm using makes it direct to the method of type get, but I need it to be to the method of type post.

[HttpPost]
public async Task<IActionResult> CurrentWork()
{
    // ....
    return RedirectToAction("Index") 
}

I apologize for my English. I hope I was clear enough.

I appreciate your help.

I'm trying to redirect from an action method to another action method of type post, specifically, since there is another action method with the same name as the one I'm trying to redirect to, but of type get. I tried to do the redirect with the (redirecttoaction) statement but it always redirects to the httpget action method and I need it to redirect to the httppost action method of the same name.

CodePudding user response:

You can try:

[HttpPost]
public async Task<IActionResult> CurrentWork()
{
    // Gets or sets the URL to redirect to.
    var url = Url.Action("Index");

    return new RedirectResult(url, false, true); 
}

See description of the third parameter preserveMethod in theRedirectResult() method:

/// <param name="preserveMethod">If set to true, make the temporary redirect (307) or permanent redirect (308) preserve the initial request method.</param>

And see the following post on the Microsoft forums: Redirect to Post Method/Action

REDIRECTING IS NOTH THE PROBLEM...the problem is making the other controller read the post data. As @CodeHobo pointed out, the only way is the first controller read the post data int its ViewModel and then put them into TempData for the second controller that expect a different viewmodel. However the point is that the second controller DON'T know that the request has been redirected and that its data are available in tempdata instead than int its ViewModel.


RedirectResult Class

  • Related