2012-05-22 11 views
9

Sto utilizzando la convalida remota per verificare la disponibilità del nome utente durante la registrazione per la mia applicazione asp.net mvc 3 (C#).Esegui qualcosa sulla risposta di successo per la convalida remota in mvc

Sto usando MVC convalida attributo remoto come:

[Remote("IsUserNameAvailable", "User")] 
public string UserName { get; set; } 

Quando torno questo:

return Json(true, JsonRequestBehavior.AllowGet); 

Poi voglio realizzare qualcosa come impostare il valore di campo nascosto, che è di ritorno da azione o mostra l'immagine icona verde. E voglio anche restituire l'ID con vero.

Come raggiungere questo obiettivo?

In breve, voglio fare qualcosa per il successo.

risposta

19

Un modo per raggiungere questo obiettivo è quello di aggiungere un'intestazione di risposta HTTP personalizzata dall'azione di convalida:

public ActionResult IsUserNameAvailable(string username) 
{ 
    if (IsValid(username)) 
    { 
     // add the id that you want to communicate to the client 
     // in case of validation success as a custom HTTP header 
     Response.AddHeader("X-ID", "123"); 
     return Json(true, JsonRequestBehavior.AllowGet); 
    } 

    return Json("The username is invalid", JsonRequestBehavior.AllowGet); 
} 

Ora sul client che, ovviamente, hanno un modulo standard e un campo di input per il nome utente:

@model MyViewModel 
@using (Html.BeginForm()) 
{ 
    @Html.EditorFor(x => x.UserName) 
    @Html.ValidationMessageFor(x => x.UserName) 
    <button type="submit">OK</button> 
} 

e ora l'ultimo pezzo del puzzle è quello di collegare un gestore complete alla remote regola sul campo nome utente:

$(function() { 
    $('#UserName').rules().remote.complete = function (xhr) { 
     if (xhr.status == 200 && xhr.responseText === 'true') { 
      // validation succeeded => we fetch the id that 
      // was sent from the server 
      var id = xhr.getResponseHeader('X-ID'); 

      // and of course we do something useful with this id 
      alert(id); 
     } 
    }; 
}); 
+0

wow .... fantastico ....... grazie mille ...... –

Problemi correlati