I want to execute a POST action by redirecting to another controller. My issue is how to do it with two same name actions.
CartLinesController.cs
// GET: CartLines/Create
public IActionResult Create(){}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(parameters){}
I'm calling these actions from another controller.
ProductsController.cs
public IActionResult AddToCart(int id)
{
TempData["ProductId"] = id;
return RedirectToAction("Create", "CartLines");
}
The issue is this RedirectToAction is calling the GET: Create action instead of the POST one. Is there a way to specify this?
CodePudding user response:
You should do it manually. First of all redirect to a GET route. In that route, return a HIDDEN form with auto-submit (maybe javascript wise) to your POST action with POST method.
See this, HTTP-redirection does not support POST out of the box.
CodePudding user response:
HTTP doesn't support redirection to a page using POST. When you redirect somewhere, the HTTP "Location" header tells the browser where to go, and the browser makes a GET request for that page.
You can redirect to the Get method first, and pass a bool value to distinguish whether to execute automatically or manually. For example:
public IActionResult AddToCart(int id)
{
TempData["ProductId"] = id;
return RedirectToAction("Create", "CartLines",new { parameter = true});
}
public IActionResult Create(bool? parameter)
{
ViewData["parameter"] = parameter;
return View();
}
Then judge whether ViewData["parameter"]
exists in the view, and if so, use JavaScript to automatically call the post method.