Ajax发布到控制器后返回视图 [英] Return view after ajax post to controller

查看:88
本文介绍了Ajax发布到控制器后返回视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过邮局用ajax发送一些json数据

I'm sending some json data with ajax by post

function SendF() {

$.ajax({
    url: '@Url.Action("Summary")',
    type: 'POST',
    data: JSON.stringify(flags),
    contentType: "application/json;charset=utf-8",
    success: function() {

    },
    error: function() {
        alert("Oops! We've experienced a connection problem!");
    }
});
}

给我的控制器

 [HttpPost]
        public ActionResult Summary(List<string> flagsChecked)
        {

             [...]

                return View(flags);
        }

并尝试返回一个包含我处理过的数据的视图,但是我想这不会发生,因为ajax完全是关于异步http请求的.如何将代码更改为同步代码?

and tried returning a view with data I've processed, but I guess it's not gonna happen since ajax is all about asynchronous http requests. How do I change my code to be synchronous?

推荐答案

使用ajax的整个想法是为用户提供部分页面更新体验.如果您正在进行ajax调用,一旦完成,并且您正在重定向到另一个页面,则不会为用户提供部分页面更新体验.它看起来与普通表单Submit(全页提交)非常相似.

The whole idea behind using ajax is to give the user the partial page update experience. If you are making an ajax call and once that is done and you are doing a redirect to another page, it does not give the partial page update experience to user. It looks very similar to the normal form submit(full page submit).

如果绝对必须通过ajax将数据发送到服务器,但是要在ajax调用成功完成后进行重定向,则可以在successdone回调事件中的$.ajax方法.

If you absolutely have to send the data to server via ajax , but want to do the redirect after the ajax call is successfully finished, you can do that using javascript in the success or done callback event on the $.ajax method.

您要做的就是将location.href属性设置为新的网址.

All you have to do is, set the location.href property to the new url.

var flags = ["aa", "bb", "cc"];

$.ajax({
    url: '@Url.Action("Summary")',
    type: 'POST',
    data: JSON.stringify(flags),
    contentType: "application/json;charset=utf-8"
}).done(function(res) {
     window.location.href = res.newUrl;
}).fail(function(xhr, a, error) {
      console.log(error);
});

这假定您的服务器操作方法返回具有newUrl属性的JSON响应,其中包含要重定向到的网址.

This assumes that your server action method returns a JSON response with the newUrl property which contains the url you want to redirect to .

[HttpPost]
public ActionResult Summary(List<string> flagsChecked)
{
    return Json(new { newUrl = Url.Action("Index","Home") });
}

这篇关于Ajax发布到控制器后返回视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆