开发者

Mvc json response check for true/false

开发者 https://www.devze.com 2023-02-11 19:40 出处:网络
I need to check if \"success\" is true or false. i get the following json response back from action:

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

{"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(开发者_StackOverflow社区'.inputBtn').remove();
        } else {
            var obj = $(this).parents('.row');
            serverError(obj, data.message);
        }
    });


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:

[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);
        }
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消