Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mvc json response check for true/false

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('.inputBtn').remove();
        } else {
            var obj = $(this).parents('.row');
            serverError(obj, data.message);
        }
    });
like image 903
ShaneKm Avatar asked Feb 15 '11 20:02

ShaneKm


1 Answers

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);
        }
    }
});
like image 184
Darin Dimitrov Avatar answered Oct 15 '22 19:10

Darin Dimitrov