AJAX POST to MVC Controller showing 302 error

一笑奈何 提交于 2019-12-23 09:22:12

问题


I want to do AJAX POST in my MVC View. I've written the following:

Script Code in View

$('#media-search').click(function () {
    var data = { key: $('#search-query').val() };

    $.ajax({
        type: 'POST',
        url: '/Builder/Search',
        data: JSON.stringify(data),
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            $('.builder').empty();
                alert("Key Passed Successfully!!!");
        }
    });
});

Controller Code

[HttpPost]
public ActionResult Search(string key)
{
    return RedirectToAction("Simple", new { key=key });
}

But on AJAX POST I am getting the 302 found Error


回答1:


The '302' response code is a redirect. Your controller action explicitly returns a RedirectToAction, which simply returns a 302. Since this redirect instruction is consumed by your AJAX call and not directly by your browser, if you want your browser to be redirected, you will need to do the following:

$.ajax({
     type: 'POST',
     url: '/Builder/Search',
     data: JSON.stringify(data),
     dataType: 'json',
     contentType: 'application/json; charset=utf-8',
     success: function (data) {
          if (data.redirect) {
              window.location.href = data.redirect;
          }
          $('.builder').empty();
          alert("Key Passed Successfully!!!");
     }
});

If not, you'll need to return something more meaningful than a redirect instruction from your controller.



来源:https://stackoverflow.com/questions/16118956/ajax-post-to-mvc-controller-showing-302-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!