猿问

对 AJAX 帖子进行验证检查并返回错误消息

我有一个 AJAX 帖子可以做到这一点。


$.ajax({

    type: "POST",

    url: "@MyWebSite.Url/myController/myView",

    contentType: "application/json; charset=utf-8",

    data: JSON.stringify({ myModel: myData }),

    dataType: "json",

    traditional: true,

    success: function () {

        alert('Success!');

    },

    error: function () {

        alert('Error! ');

    }

})

我的控制器进行了验证检查,但没有正确返回错误消息。这是我的控制器的样子:


if (totalQty < part.QtyInItem) {

    //ModelState.AddModelError("", "My ERROR Message");

    //RedirectToAction("myControler", myModel);

    return this.Json(new { success = false, message = "My Error Message" });

}

当我尝试向模型状态添加错误时,它只返回“错误!” 而不是我与之关联的错误消息。当我尝试执行 this.JSON 返回时,它会向视图返回“成功”而不是错误消息。


我怎样才能对我的 AJAX 帖子进行验证检查


牧羊人nacy
浏览 96回答 1
1回答

慕虎7371278

您必须将数据对象添加到您的函数中。$.ajax({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type: "POST",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url: "@MyWebSite.Url/myController/myView",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; contentType: "application/json; charset=utf-8",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; JSON.stringify({ myModel: myData }),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dataType: "json",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; traditional: true,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; success: function (data) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert(data.message);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; error: function () {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert('Error! ');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }如果您仍然遇到错误,您应该检查您的控制台是否有任何服务器错误。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答