【问题标题】:How to redirect using ajax in MVC如何在 MVC 中使用 ajax 进行重定向
【发布时间】:2018-05-31 10:51:30
【问题描述】:

我有点击按钮,它接受输入值并重定向到javascript中的另一个页面,看起来像window.location = "Action Param1=value1&Param2=Value2"。但是该方法使用了我想避免的查询字符串。 所以我想到了使用ajax

   ` $.ajax({
            type: "POST",
            url: "/MyController/MyAction",
            data: '{Param1:"value1",Param2:"value2"}',
            contentType: "application/json,charset=utf-8",
            dataType: "json",
            success: function () {
            }
        });`

这确实调用了控制器,但不返回任何内容。 我不知道我在这里做错了什么,将不胜感激。

【问题讨论】:

  • 您可以使用数据填充表单并将表单的action 属性设置为您要重定向到的页面。否则,只需使用 Ajax 发布,然后在成功处理程序中发布 window.location.href = "the-other-url"
  • ajax 的全部意义在于保持在 SAME 页面上。如果你想重定向不要使用 ajax!只需进行正常提交,省去自己编写毫无意义的脚本

标签: javascript ajax model-view-controller


【解决方案1】:

如果它只包括重定向到页面

return JavaScript("window.location = 'http:yourlink'");

是最好的选择,但您想传递数据,请按照以下方式进行操作

function redi() {
        var date = new Date(); 
        var link = '@Url.Action("ActionMethod", "Home")';  var args = {
            param1: date.toISOString(),  
            param2: date.toISOString(),
            param3: 'yourdata'
        }; 

        $.ajax({
            type: "GET",
            url: link, 
            data: args, 
            dataType: "json",
            success: function (data) {

                window.location.href = data.redirecturl; 

            },
            error: function (httpRequest, textStatus, errorThrown) {   
                alert("Error: " + textStatus + " " + errorThrown + " " + httpRequest);
            }
        });

}

控制器:

[HttpGet]
    public ActionResult ActionMethod(DateTime param1, DateTime param2, string param3)
    {
        return Json(new { redirecturl = "http:yourlink" }, JsonRequestBehavior.AllowGet);

}

【讨论】:

    猜你喜欢
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    • 2016-06-26
    相关资源
    最近更新 更多