2012-10-19 5 views
5

Ho un metodo in un controllore che assomiglia a questo:genera un errore di nuovo a jQuery da un MVC HttpPost

[HttpPost] 
public void UnfavoriteEvent(int id) 
{ 
    try 
    { 
     var rows = _connection.Execute("DELETE UserEvent WHERE UserID = (SELECT up.UserID FROM UserProfile up WHERE up.UserName = @UserName) AND EventID = @EventID", 
      new { EventID = id, UserName = User.Identity.Name }); 
     if (rows != 1) 
     { 
      Response.StatusCode = 500; 
      Response.Status = "There was an unknown error updating the database."; 
      //throw new HttpException(500, "There was an unknown error updating the database."); 
     } 
    } 
    catch (Exception ex) 
    { 
     Response.StatusCode = 500; 
     Response.Status = ex.Message; 
     //throw new HttpException(500, ex.Message); 
    } 
} 

E come potete vedere ho provato un paio di modi diversi per lanciare questo errore indietro. Nel JavaScript ho il blocco successivo a chiamare questo metodo:

var jqXHR; 
if (isFavorite) { 
    jqXHR = $.ajax({ 
     type: 'POST', 
     url: '/Account/UnfavoriteEvent', 
     data: { id: $("#EventID").val() } 
    }); 
} 
else { 
    jqXHR = $.ajax({ 
     type: 'POST', 
     url: '/Account/FavoriteEvent', 
     data: { id: $("#EventID").val() } 
    }); 
} 

jqXHR.error = function (data) { 
    $("#ajaxErrorMessage").val(data); 
    $("#ajaxError").toggle(2000); 
}; 

Ora, quello che voglio fare è ottenere l'errore che si verifica ributtato alla funzione jqXHR.error in modo che possa gestire in modo corretto.

Attualmente il codice che non sia commentata genera un'eccezione dicendo che il testo che sto mettendo in Status non è consentito, e il codice commentato in realtà restituisce la pagina di errore standard, come la risposta (non sorprende davvero).

Così, ho un paio di domande:

  1. Come faccio a buttare l'errore correttamente?
  2. Che cosa fa la proprietà Response.Status?

Grazie a tutti!

+0

Poiché si sta rilevando un'eccezione generica, non invieremo il messaggio specifico al client. Questo potrebbe finire per essere informazioni sensibili sulla tua applicazione. Se rilevi eccezioni di dominio personalizzate in cui hai il controllo del messaggio, puoi inviarle al client, ma per l'eccezione generica devi inviare un messaggio generico. – BZink

+0

@BZink, ottimo punto. Grazie. –

risposta

3

Sarete abili per ottenere lo stato della risposta dal lato javascript, effettuando le seguenti operazioni:

$.ajax({ 
    type: 'POST', 
    url: '/Account/UnfavoriteEvent', 
    data: { id: $("#EventID").val() }, 
    success: function(data, textStatus, jqXHR) { 
     // jqXHR.status contains the Response.Status set on the server 
    }, 
    error: function(jqXHR, textStatus, errorThrown) { 
     // jqXHR.status contains the Response.Status set on the server 
    }}); 

Come si può vedere, si deve passare la funzione per error alla funzione ajax ... in te Ad esempio, si imposta la funzione sulla proprietà error di jqXHR senza alcun effetto.

documentazione sugli eventi ajax

docs jQuery dire che la stringa di errore arriverà nel parametro errorThrown.

Non utilizzare Response

Invece, si dovrebbe tornare HttpStatusCodeResult:

[HttpPost] 
public void UnfavoriteEvent(int id) 
{ 
    try 
    { 
     var rows = _connection.Execute("DELETE UserEvent WHERE UserID = (SELECT up.UserID FROM UserProfile up WHERE up.UserName = @UserName) AND EventID = @EventID", 
      new { EventID = id, UserName = User.Identity.Name }); 
     if (rows != 1) 
     { 
      return new HttpStatusCodeResult(500, "There was an unknown error updating the database."); 
     } 
    } 
    catch (Exception ex) 
    { 
     return new HttpStatusCodeResult(500, ex.Message); 
    } 
} 
+0

Questo mi ha indotto nel metodo di errore nel JavaScript, quindi grazie! Ma la stringa di errore che voglio non è in 'Response.Status'. Che cosa sto facendo male sul lato server e come faccio a mandare quel messaggio semplice al client? –

+0

Grazie, è esattamente ciò di cui avevo bisogno! –

Problemi correlati