Home > Mobile >  How to redirect to the post overload of an IActionResult
How to redirect to the post overload of an IActionResult

Time:12-01

I'm working on an Apsp.Net 6 project targeted .Net6.

I have this ActionResult:

    [Route( nameof(Recreate))]
    public async Task<IActionResult> Recreate()
    {
       //Some code here
    }

    [HttpPost]
    [Route( nameof(Recreate))]
    public async Task<IActionResult> Recreate(StudentYearlyResultReCreateVm model)
    {
       //Some code here
    }

Now I have another ActionResult described like this :

    [Route( nameof(RecreateWithId))]
    public async Task<IActionResult> RecreateWithId(int id)
    {
        var result = await _studentYearlyResultRepository.GetByIdAsync( id );
        var modelObj = new StudentYearlyResultReCreateVm() {StudentId = result.StudentId , AcademicYearId = result.AcademicYearId};

        return RedirectToAction( nameof( Recreate ) , modelObj );
    }

The problem : The problem is in RecreateWithId method I try to RedirectToAction to the post overload for Recreate action, but all I got is just redirected to the Get one.

So please how I can redirect to the post overload of Recreate ? Thank you in advance.

CodePudding user response:

When you return an action using RedirectToAction, the server returns a 3xx Response to browser with Location header to that Url. Browser then proceeds to access that URL with GET verb, there is no way to change this unless you use Javascript to submit a form from that GET Url.

As for your question, I think a good solution should separation of concern by having a Service for processing:


[Route("api")]
public class ApiController
{

    ApiService service;
    public ApiController(ApiService service)
    {
        this.service = service;
    }

    [HttpGet, Route("")]
    public async Task OnGetAsync()
    {
        await this.service.DoSomethingAsync();
    }

    [HttpPost, Route("")]
    public async Task<IActionResult> OnPostAsync()
    {
        await this.service.DoSomethingElseAsync();

        // If you call this, don't redirect or it may call DoSomethingAsync twice
        await this.service.DoSomethingAsync();
        
        return this.RedirectToAction(nameof("OnGetAsync"));
    }

}

CodePudding user response:

A quick, maybe dirty(?), solution.

[Route( nameof(RecreateWithId))]
public async Task<IActionResult> RecreateWithId(int id)
{
    var result = await _studentYearlyResultRepository.GetByIdAsync( id );
    var modelObj = new StudentYearlyResultReCreateVm() {StudentId = result.StudentId , AcademicYearId = result.AcademicYearId};

    return await Recreate(modelObj );
}
  • Related