views:

802

answers:

2

Hi,

I am trying to call an ASP.NET MVC actionMethod via the JQuery ajax method. My code is as follows:

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

and my action method is:

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

    return " ";
}

I return an empty string as I read somewhere that if the content-length is 0 then it can cause problems, when the return type is a string I get an alert box saying "Error: error undefined" and the second alert box is empty.

If I make the return type void I get an alert saying "Error: parsererror undefined" and the second alert is as follows:

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
+3  A: 

I would not advise to return an empty string. Since you have set the dataType to json jquery will eval the response.

You should always return a logical message.

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

N.B inside the success you are using $(tr).remove(); There is no need as your tr variable is already a jQuery object so tr.remove will work just fine.

redsquare
+3  A: 

Your jQuery call expects Json in return of the request. So :

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

And also I agree with redsquare, it's better to return a logical message like this :

[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");
    }
}
çağdaş