为什么在ajax帖子调用后得到json响应页面?

问题描述

我有一个aps.net MVC5 Web应用程序,我有一个类似这样的控制器动作发布方法,

   [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Set(int id)
        {
            DbHelper dbHelper = new DbHelper();
            dbHelper.Update<News>("update news set ispublished = 1,publishdate = @PublishDate  where newsid = @NewsId",new { NewsId = id,PublishDate = DateTime.Now });
            return Json(new { success = true,message = "added successfully!",redirectToUrl = Url.Action("NewsList","Home") },JsonRequestBehavior.AllowGet);
        }

现在,当我从View调用此方法时,

 $(document).on("click",".set",function () {

        var mId = $(this).attr("data-model-id");
        $.ajax({
            url: "@Url.Action("Set","Home")",data: { "id": mId },contentType: 'application/json',type: 'POST',dataType:'json',success: function (response) {
                if (response.success) {
                    window.location.href = response.redirectToUrl;
                    dt.ajax.reload();

                    $.notify(data.message,{
                        globalPosition: "top center",className: "success"
                    });
                }
            },error: function (response) {
                $.notify(response.message,{
                    globalPosition: "top center",className: "success"
                });
            }
        });
    });

我总是得到这个enter image description here

我希望将重定向到home / newslist网址。我尝试更改ajax call的所有参数,添加和删除它们,无论我做什么,我总是会进入此页面。

解决方法

尝试从ajax中删除“错误”功能后进行检查。您也可以尝试以下方法:

$(document).on("click",".set",function () {

    var mId = $(this).attr("data-model-id");
    $.ajax({
        url: "@Url.Action("Set","Home")",data: { "id": mId },contentType: 'application/json',type: 'POST',dataType:'json',success: function (response) {
            if (response.success) {
                window.location.href = response.redirectToUrl;
                dt.ajax.reload();

                $.notify(data.message,{
                    globalPosition: "top center",className: "success"
                });
            }
        },error: function (jqXHR,textStatus,errorThrown) {
            $.notify(errorThrown,{
                globalPosition: "top center",className: "success"
            });
        }
    });
});

检查成功函数是否正在调用。

,

如果需要在ajax响应中返回完整的HTML页面,则需要通过一些更改来更改Controller方法。

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Set(int id)
{
       DbHelper dbHelper = new DbHelper();
       dbHelper.Update<News>("update news set ispublished = 1,publishdate = @PublishDate  where newsid = @NewsId",new { NewsId = id,PublishDate = DateTime.Now });
       //return Json(new { success = true,message = "added successfully!",redirectToUrl = Url.Action("NewsList","Home") },JsonRequestBehavior.AllowGet);
       return view("ViewName");
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...