为什么Ajax请求始终显示错误消息,而JSon总是返回true?

时间:2017-11-21 05:23:26

标签: jquery asp.net json ajax asp.net-mvc

我不明白为什么会发生这种错误。我有一个名为SitePlanSaveTask的方法,它创建新计划并在成功保存时返回Json True。现在,当我调试方法时,计划成功保存,Json始终返回true。但在视图中它总是给出错误信息。我的问题是,如果我的Json返回true,那么为什么它不会进入Ajax请求条件。

控制器:

  public ActionResult Create()
    {

        if (!User.IsInRole("Management"))
        {
            return RedirectToAction("AccessDenied", "Error");
        }

        ViewBag.ProjectId = new SelectList(db.Project, "Id", "Name");
        ViewBag.StartDate = DateTime.Now.Date;
        ViewBag.EndDate = DateTime.Now.Date;
        ViewBag.PlanDate = DateTime.Now.ToShortDateString();
        var status = new SelectList(new List<SelectListItem> { new SelectListItem { Text = "Active", Value = "A" }, new SelectListItem { Text = "Inactive", Value = "I" }, }, "Value", "Text");
        ViewBag.Status = status;
        List<ProjectTask> taskList = db.ProjectTask.ToList();
        ViewBag.ProjectTask = taskList;
        return View();
    }

  public JsonResult SitePlanSaveTask(string name)
    {
        ProjectTask projectTask = new ProjectTask();
        projectTask.Name = name;
        var check = db.ProjectTask.Where(x => x.Name == name).Count();
        bool flag = false;
        if (check == 0)
        {
            db.ProjectTask.Add(projectTask);

            flag = db.SaveChanges() > 0;
        }

        return Json(new { flag = flag, Id = projectTask.Id }, JsonRequestBehavior.AllowGet);
    }

查看:

  $("#btnAddTask").click(function (e) {
    e.preventDefault();
    $.ajax({

        type: "POST",
        url: "/ProjectSitePlanTasks/SitePlanSaveTask",
        data: {
            name: $("#TName").val()
        },
        dataType: "json",
        contentType: "application/json",
        success: function (result) {
            console.log(result);
            if (result.flag)
            {
                alert("Record saved successfully!");
                window.location = "/ProjectSitePlanTasks/Create";

            }
            else
            {
                alert("Saving failed!");
            }

        },
       error: function (result)
       {
            alert('error');
       }
    });
});

3 个答案:

答案 0 :(得分:0)

默认情况下,所有控制器操作方法都是httpget。所以你必须使用下面的代码片段将它转换为httppost。

[HttpPost]
public JsonResult SitePlanSaveTask(string name)
{
 ....
 ....
}

答案 1 :(得分:0)

试试JSON.stringify(result)。然后选择result.flag。这可能有效。

答案 2 :(得分:0)

试过吗?

[HttpPost]
public JsonResult SitePlanSaveTask(string name){
...
}