2011-02-15 79 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); 
     } 
    } 
});