Domanda

Sto cercando di chiamare un ASP.NET MVC actionMethod tramite il metodo ajax JQuery. Il mio codice è il seguente:

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

e il mio metodo di azione è il seguente:

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

    return " ";
}

torno una stringa vuota come ho letto da qualche parte che se il contenuto di lunghezza è pari a 0, allora può causare problemi, quando il tipo di ritorno è una stringa ottengo una finestra di avviso che dice "Errore: errore non definito" e la seconda finestra di avviso vuoto.

Se faccio il tipo di ritorno void ricevo un messaggio che dice "Errore: non definito ParserError" e il secondo avviso è la seguente:

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
È stato utile?

Soluzione

Non consiglierei per restituire una stringa vuota. Dal momento che è stato impostato il tipo di dati a JSON jQuery eval la risposta.

Si dovrebbe sempre restituire un messaggio logico.

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

NB all'interno del successo che si sta utilizzando $(tr).remove(); Non c'è bisogno, come la variabile TR è già un oggetto jQuery così tr.remove funzionano bene.

Altri suggerimenti

La chiamata jQuery si aspetta JSON in cambio della richiesta. Quindi:

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

E anche sono d'accordo con redsquare , è meglio per restituire un messaggio logico in questo modo:

[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");
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top