2011-02-15 84 views
8

我需要检查“成功”是真是假。我碰到下面的JSON响应回从行动:Mvc json响应检查真/假

{“成功”:真正}

我怎么可以,如果真或假的检查。我尝试过,但它不起作用。它回来未定义

$.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); 
     } 
    }); 
+0

我想我想通了。我是这样做的:return Json(new {success = true,message =“this is test”},“text/html”);与“文本/ HTML”,当我删除它的作品。不知道,但由于某种原因,IE浏览器需要此? – ShaneKm 2011-02-15 20:43:41

回答

24

你的控制器动作应该是这样的:

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

个人而言,我会使用HTTP DELETE动词,似乎更approapriate服务器上删除的资源和更REST风格:

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

然后:

$.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); 
     } 
    } 
});