2009-07-22 34 views
2

JQuery ajaxメソッドを使用してASP.NET MVC actionMethodを呼び出そうとしています。ASP.NET MVCアプリケーションでJQuery ajax parsererror

$('.Delete').live('click', function() { 
    var tr = $(this).parent().parent(); 

    $.ajax({ 
     type: 'DELETE', 
     url: '/Routing/Delete/' + tr.attr('id'), 
     contentType: 'application/json; charset=utf-8', 
     data: '{}', 
     dataType: 'json', 
     error: function(XMLHttpRequest, textStatus, errorThrown) { 
      alert("Error: " + textStatus + " " + errorThrown); 
      alert(XMLHttpRequest.getAllResponseHeaders()); 
     }, 
     success: function(result) { 
      // Remove TR element containing waypoint details 
      alert("Success"); 
      $(tr).remove(); 
     } 
    }); 
}); 

と私のアクションメソッドは次のとおりです:次のように私のコードがある

[AcceptVerbs(HttpVerbs.Delete)] 
public string Delete(int id) 
{ 
    // Deletion code 

    return " "; 
} 

私はコンテンツ長が0であれば、それは問題を引き起こす可能性があることをどこかで読んで、私は、空の文字列を返します戻り値の型は文字列です。「エラー:エラーが定義されていません」という警告ボックスが表示され、2番目の警告ボックスは空です。

私は戻り値の型がvoidを作る場合、私は警告が言ってもらう「エラー:未定義parsererror」とは以下のように、第2の警告がある:

Server: ASP.NET Development Server/9.0.0.0 
Date: Wed, 22 Jul 2009 08:27:20 GMT 
X-AspNet-Version: 2.0.50727 
X-AspNetMvc-Version: 1.0 
Cache-Control: private 
Content-Length: 0 
Connection: Close 
+0

うーん私の答えは同じと最初でした! – redsquare

+0

私の悪い、今すぐソート! – Fermin

答えて

4

私は空の文字列を返すように助言しません。 dataTypeをjsonに設定したので、jqueryは応答を評価します。

常に論理メッセージを返す必要があります。あなたが$(tr).remove()を使用している成功内部

return Json(new { success = "true" });

N.B。 tr変数がすでにjQueryオブジェクトである必要はありませんので、 tr.removeはうまく動作します。

5

jQueryの呼び出しでは、要求の代わりにJsonが必要です。だから、:

[AcceptVerbs(HttpVerbs.Delete)] 
public JsonResult Delete(int id) { 
    // Deletion code 
    return Json(""); 
} 

そしてまた、私はそれがこのような論理的なメッセージを返す方が良いでしょう、redsquareに同意:

[AcceptVerbs(HttpVerbs.Delete)] 
public JsonResult Delete(int id) { 
    // Deletion code 
    return Json(new { Success = true }); 
} 

//then in your jQuery function you can check the result this way : 
success: function(result) { 
    if (result.Success) { 
     alert("it was deleted!"); 
    } 
    else { 
     alert("something went wrong"); 
    } 
} 
関連する問題