【问题标题】:unable to redirect after json postjson发布后无法重定向
【发布时间】:2012-06-03 01:31:48
【问题描述】:

我的视图中有以下 jquery 代码

<script type="text/javascript">
    $(document).ready(function () {
        $("#dialog-confirm").dialog({
            autoOpen: false,
            modal: true,
            resizable: false,
            width: '500px'
        });

        $(".deleteLink").click(function (e) {
            e.preventDefault();
            var targetUrl = $(this).attr("href");
            var dID = $(this).attr("id");
            $("#dialog-confirm").dialog({
                buttons: {
                    "Confirm": function () {
                        $.ajax({
                            url: '@Url.Action("DeleteSession")',
                            type: 'POST',
                            data: { id: dID },
                            success: function (data) {
                                    window.location.herf = data.redirectToUrl;
                            }
                        });
                    },
                    "Cancel": function () {
                        $(this).dialog("close");
                    }
                }
            });

            $("#dialog-confirm").dialog("open");
        });
    });
</script>

触发对话框的这个链接是;

@Html.ActionLink("Delete", "", new { id = s.ID },new { @class = "deleteLink", id = s.ID})

控制器方法DeleteSession返回Json结果。

控制器:

[HttpPost]
public JsonResult DeleteSession(int id)
{

    try
    {
        sRep.DeleteSession(id);
        return Json(new {success = true, redirectToUrl = Url.Action("Index")});
    }
    catch (Exception e)
    {
        return Json(new {success = false, redirectToUrl = Url.Action("DisplayError", new { eerror = 
                                    "Unable to delete the course. " + "Internal error: " + e.Message})});
    }

}

我检查了Json 结果,看起来还不错。唯一的问题是window.location.herf = data.redirectToUrl; 它不起作用。页面未重定向,对话框仍在屏幕上。

知道我做错了什么吗?

【问题讨论】:

  • 哈哈,这不是我唯一的错别字……我显然需要离开电脑一段时间。

标签: jquery json asp.net-mvc-3 jquery-ui modal-dialog


【解决方案1】:

我认为你的意思是 window.location.href

您的原始代码:

window.location.herf = data.redirectToUrl;

应改为:

window.location.href = data.redirectToUrl;

【讨论】:

  • 不幸的是,当您长时间编写一段代码时,通常会出现这种情况。这就是为什么每隔一段时间休息一下是件好事。第一次看代码或稍作休息后更容易发现小错误。
【解决方案2】:

你也可以使用

$(window.location).attr('href',data.redirectToUrl);

【讨论】:

  • 这样做有什么好处吗?当原生js更短更清晰时,为什么要使用jquery wrapper?
  • @serrghi 更多的是跨浏览器支持问题......而且,我是 jquery 的忠实粉丝......我想这完全是个人喜好
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-08
  • 1970-01-01
相关资源
最近更新 更多