How to get an ASP.NET MVC Ajax response to redirec

2020-01-24 02:22发布

I am using the Ajax.BeginForm to create a form the will do an ajax postback to a certain controller action and then if the action is successful, the user should get redirected to another page (if the action fails then a status message gets displayed using the AjaxOptions UpdateTargetId).

using (Ajax.BeginForm("Delete", null,
        new { userId = Model.UserId },
        new AjaxOptions { UpdateTargetId = "UserForm", LoadingElementId = "DeletingDiv" },
        new { name = "DeleteForm", id = "DeleteForm" }))
   {
    [HTML DELETE BUTTON]
   }

If the delete is successful I am returning a Redirect result:

[Authorize]
public ActionResult Delete(Int32 UserId)
{
    UserRepository.DeleteUser(UserId);
    return Redirect(Url.Action("Index", "Home"));
}

But the Home Controller Index view is getting loaded into the UpdateTargetId and therefore I end up with a page within a page. Two things I am thinking about:

  1. Either I am architecting this wrong and should handle this type of action differently (not using ajax).
  2. Instead of returning a Redirect result, return a view which has javascript in it that does the redirect on the client side.

Does anyone have comments on #1? Or if #2 is a good solution, what would the "redirect javascript view" look like?

14条回答
戒情不戒烟
2楼-- · 2020-01-24 02:36

You can use JavascriptResult to achieve this.

To redirect:

return JavaScript("window.location = 'http://www.google.co.uk'");

To reload the current page:

return JavaScript("location.reload(true)");

Seems the simplest option.

查看更多
地球回转人心会变
3楼-- · 2020-01-24 02:36

Using JavaScript will definitely do the job.

You can also use Content if this is more your style.

Example:

MVC Controller

[HttpPost]
public ActionResult AjaxMethod()
{
    return Content(@"http://www.google.co.uk");
}

Javascript

$.ajax({
    type: 'POST',
    url: '/AjaxMethod',
    success: function (redirect) {
        window.location = redirect;
    }
});
查看更多
不美不萌又怎样
4楼-- · 2020-01-24 02:38

As ben foster says you can return the Javascripts and it will redirect you to the desired page.

To load page in the current page:

return JavaScript("window.location = 'http://www.google.co.uk'");'

To load page in the new tab:

return JavaScript("window.open('http://www.google.co.uk')");
查看更多
Evening l夕情丶
5楼-- · 2020-01-24 02:42

You can simply do some kind of ajax response filter for incomming responses with $.ajaxSetup. If the response contains MVC redirection you can evaluate this expression on JS side. Example code for JS below:

$.ajaxSetup({
    dataFilter: function (data, type) {
        if (data && typeof data == "string") {
            if (data.indexOf('window.location') > -1) {
                eval(data);
            }
        }
        return data;
    }
});

If data is: "window.location = '/Acount/Login'" above filter will catch that and evaluate to make the redirection.

查看更多
叛逆
6楼-- · 2020-01-24 02:43

You can return a JSON with the URL and change the window.location using JavaScript at client side. I prefer this way than calling a JavaScript function from the server, which I think that it's breaking the separation of concerns.

Server side:

return Json(new {result = "Redirect", url = Url.Action("ActionName", "ControllerName")});

Client side:

if (response.result == 'Redirect')
    window.location = response.url;

Of course you can add more logic because there could be an error on the server side and in that case the result property could indicate this situation and avoid the redirection.

查看更多
Luminary・发光体
7楼-- · 2020-01-24 02:43

You can get a non-js-based redirection from an ajax call by putting in one of those meta refresh tags. This here seems to be working: return Content("<meta http-equiv=\"refresh\" content=\"0;URL='" + @Url.Action("Index", "Home") + "'\" />");

Note: I discovered that meta refreshes are auto-disabled by Firefox, rendering this not very useful.

查看更多
登录 后发表回答