jQuery Mvc json 响应检查真/假

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5009256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:23:03  来源:igfitidea点击:

Mvc json response check for true/false

jqueryasp.netasp.net-mvcasp.net-mvc-3

提问by ShaneKm

I need to check if "success" is true or false. i get the following json response back from action:

我需要检查“成功”是真是假。我从操作中得到以下 json 响应:

{"success":true}

{“成功”:真}

how can i check it if true or false. i tried this but it doesn't work. it comes back undefined

我如何检查它是真还是假。我试过这个,但它不起作用。它回来未定义

    $.post("/Admin/NewsCategory/Delete/", { id: id }, function (data) {
        alert(data.success);
        if (data.success) {
            $(this).parents('.inputBtn').remove();
        } else {
            var obj = $(this).parents('.row');
            serverError(obj, data.message);
        }
    });

回答by Darin Dimitrov

Your controller action should look like this:

您的控制器操作应如下所示:

[HttpPost]
public ActionResult Delete(int? id)
{
    // TODO: delete the corresponding entity.
    return Json(new { success = true });
}

Personally I would use the HTTP DELETE verb which seems more approapriate for deleting resources on the server and is more RESTful:

就我个人而言,我会使用 HTTP DELETE 动词,它似乎更适合删除服务器上的资源,并且更符合 RESTful:

[HttpDelete]
public ActionResult Delete(int? id)
{
    // TODO: delete the corresponding entity.
    return Json(new { success = true, message = "" });
}

and then:

进而:

$.ajax({
    url: '@Url.Action("Delete", "NewsCategory", new { area = "Admin" })', 
    type: 'DELETE',
    data: { id: id }, 
    success: function (result) {
        if (result.success) {
            // WARNING: remember that you are in an AJAX success handler here,
            // so $(this) is probably not pointing to what you think it does 
            // In fact it points to the XHR object which is not a DOM element 
            // and probably doesn't have any parents so you might want to adapt 
            // your $(this) usage here
            $(this).parents('.inputBtn').remove();
        } else {
            var obj = $(this).parents('.row');
            serverError(obj, result.message);
        }
    }
});