没有 contentType 函数无法工作:'application/json'

Function not working without contentType: 'application/json'

我的问题是 ajax 中的成功函数有效,但错误不起作用,但如果添加到 contentType:'application/json' 工作总是错误的功能。

 $.ajax({
                    type: "POST",
                    data: { pollCodeInput: pollCodeInput, pollNameInput: pollNameInput, promotionPoints: promotionPoints },
                    url: "http://Work.local/mvc/KeyFacts/CreatePoll2",                       
                    //contentType: 'application/json',
                    success: function () {
                        openNav();
                        $('#modal').removeClass('modal-open');                         
                    },
                    error: function () {
                        alert("error!");
                    }                             
               });

            });

当我调试时,我的 Controller 工作 correctly.This 是我的 Controller;

[HttpPost]
    public ActionResult CreatePoll2(string pollCodeInput, string pollNameInput, int promotionPoints = 0)
    {
        MethodResult result = BusinessComponentRegistry.SingleInstance.PollManager.Create(pollCodeInput,
            pollNameInput, 0);
        if (result.HasErrors)
        {
            ViewBag.ErrorCreatePoll = result.Messages.ToString();
            return Json(new { success = false, responseText = "The attached file is not supported." }, JsonRequestBehavior.AllowGet);

        }
        else
        {
            ViewBag.SuccessCreatePoll = result.Messages.ToString();             
            return Json(new { success = true, error = false, responseText = "Success!!" }, JsonRequestBehavior.AllowGet);
          }
    }

首先请将所有参数设为对象

   var obj = {};
        obj.first_name = $("#FirstName").val();
        obj.last_name = $("#LastName").val();
        obj.email_id = $("#Email").val().toLowerCase();
        obj.gender = $("#Gender").val();
        obj.birth_date = $("#BirthDate").val();
        obj.address = $("#Address").val();
        obj.cell_phone = $("#Phone").val();
        obj.user_name = $("#UserName").val();
        obj.password = $("#Password").val();
        obj.security_question = $("#SecurityQuestion").val();
        obj.security_answer = $("#SecurityAnswer").val();   
        obj.role_id = $("#EmployeeType").val();
        obj.access_level = $("#AccessLevel").val();
        obj.business_id = businessId;
        obj.isActive = "true";
        obj.teamlead_id = $("#TeamleadName").val();
        obj.projectlead_id = $("#ProjectleadName").val();
        obj.manager_id = $("#ManagerName").val();

现在用这个json方法转换它们

   dataValue = JSON.stringify(obj);

并像这样使用它

  $.ajax({
        type: "POST",
        url: strUrl,
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        data: dataValue,
        async: false,
        success: onSuccess,
        error: function (err) {
            callLoader(false);
            swal({
                title: "Something Wents Wrong", text: "", type: "error",
                showCancelButton: false, closeOnConfirm: true, confirmButtonText: "OK",
            }, function (isConfirm) {
                window.location = "signin";
            });
            // console.log(err);
        }
    });
}

问题是您的 ActionResult returning OK (http 200) 因为两个分支 return 有效 Json

return Json(new ...

所以 ajax 调用总是触发 success: 回调。

在您的操作中,您处理 PollManager 未正确创建并且 return 成功 结果 到 ajax 的情况。

在该结果中有一个标志表明 "success" 是错误的,但这不是用于 success: 回调的 相同 成功- 这里没有 configuration-by-convention。您可以轻松地将该值称为其他值,例如:

return Json(new { workedlikeacharm = false ...

所以这里最好的 (IMO) 选项是保持操作原样,return 向 ajax 发送一个有效结果,并用一个标志说明要做什么,并在其中处理它success: 回调,例如:

success:function(result) {
    if (result.success == true) {
        openNav();
        $('#modal').removeClass('modal-open');
    } else {
        alert(result.responseText);
    }

但是,如果您想保留 ajax success/fail 并更改操作,那么您需要更改 returning:

if (result.HasErrors)
    return new HttpStatusCodeResult(500, "file is not supported");

现在 return 是 500 而不是 200(有效 return new Json(.. 隐含 200)然后 javascript 代码将触发 error: 回调。

或者,您可以只抛出异常(这将生成 500 状态代码结果),例如:

if (result.HasErrors)
    throw new InvalidOperationException("file is not supported");

在这两种情况下,如果您想查看消息,则必须更新 error: 处理程序以读取 http 状态消息。