简体   繁体   中英

ASP.NET Core MVC RedirectToAction isn't working

I have seen lots of questions regarding this issue but none of those resolved my problem.

My problem: my redirect action method hits the method I am redirected to, but the view stays on the same page it never changes to the redirected one.

From my Index.chstml I am creating a partial view.

From that partial view using AJAX I am submitting a request to my controller. AJAX code is below

        $.ajax({
                method: 'POST',
                url: "/Home/SubmitTest",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(arr),
                success: function (response) {
                }
            });

My controller code is here. I am receiving data from AJAX method and performing some jobs. In the end, I am trying to redirect the user to another method.

[HttpPost]
public IActionResult SubmitTest([FromBody] List<TestSubmitViewModel> data)
{
    // Rest of the code goes here
    return RedirectToAction(nameof(PipelineList));
}

The method I am redirecting to is below. Both methods are in the same controller. After redirection, I am getting hit to this method. But my view still stays in the previous URL which is

https://localhost:44339/Home/Index

but it supposed to redirected to

https://localhost:44339/Home/PipelineList

Code:

[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> PipelineList()
{
    List<PipelineViewModel> itemList = new List<PipelineViewModel>();
    /// my other code goes here             
    return View(itemList);
}

Note: my PipelineList() works fine when I am coming to this action method directly from UI. What am I doing wrong here and what can I do to redirect to the URL?

I am using .NET Core 5.

Here is my routing information from StartUp.cs :

app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller}/{action}/{id?}",
                defaults: new { controller = "Home", action="SignIn"});
        });

UPDATE Thank you guys for pointing out the problem I was having. Using AJAX was necessary for me to pass the selected values (which were from a table created by JS) from UI.

Finally, I made it work by changing my Controller and AJAX code.

Updated Controller:

[HttpPost]
public async Task<JsonResult> SubmitTest([FromBody] 
     List<TestSubmitViewModel> data)
{
    try
    {
        // my codes goes here
        return Json(new {StatusCode = statusCode });
    }
    catch (Exception)
    {
         return Json(new {StatusCode = 500 });
    }
}        

Updated AJAX:

$.ajax({
        method: 'POST',
        url: "/Home/SubmitTest",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(arr),
        success: function (response) {
        if (response.statusCode == 200) {
                var url = "/GitLab/PipelineList";
                window.location.href = url;
            } else {
                alert("error");
            }
        }
    });

I know this might not be the best solution but for now, it did work. Thanks a lot to @Sergey and @Filipe

As @Sergey says, you used the wrong senior for ajax. Ajax is normally used when you want to update part of the page instead of refreshing the whole page to increase the customer experience and page load speed. If you want to redirect to another page and there is no other specific reason, there is no need to use ajax.

You could find the ajax server has returned the right 302 redirect to the client side and it redirect to the new page:

在此处输入图像描述

The right way is directly redirect to the new page like this:

<form asp-action="SubmitTest" asp-controller="Home" method="post">
     @*Other input value you want to submit*@
    <input  type="submit" value="Click"/>
</form>

Result:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM