2013-01-09 11 views
5

Jestem nowy w MVC4. Muszę utworzyć weryfikację nazwy logowania. Po napisaniu łańcucha, kiedy wyjdziemy z pola tekstowego, powinien on pokazać, czy jest dostępny, czy nie.Jak wykonać wywołanie ajax w MVC4

The View Code jest:

@{ 
    ViewBag.Title = "Home Page"; 
} 
@section featured { 
    <section class="featured"> 
     <div class="content-wrapper"> 
      @Html.TextBox("textbox1") 
      @Html.TextBox("txtTest") 
     </div> 
    </section> 
} 
@section scripts{ 
    <script type="text/javascript"> 
     $(document).ready(function(){ 
      $('#textbox1').blur(function(){ 
       alert("a"); 
      }); 
     }); 
    </script> 
} 

Teraz zamiast alert("a"), będę musiał zadzwonić akcję. Ta akcja będzie zawierała sprawdzanie bazy danych.

Kod Kontroler:

public class HomeController : Controller 
    { 
     public ActionResult Index() 
    { 
     ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application."; 

     return View(); 
    } 
     public ActionResult SearchUser() 
     { 
      string ExistsCheck; 
      SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["conn"].ToString()); 
      SqlDataAdapter da = new SqlDataAdapter(); 
      SqlCommand cmd = new SqlCommand(); 
      DataTable dt = new DataTable(); 
      cmd = new SqlCommand("sp_UserName_Exist_tbl_UserDetails", con); 
      cmd.CommandType = CommandType.StoredProcedure; 
      cmd.Parameters.AddWithValue("@UserName", Request.Form["textbox1"]); 
      da.SelectCommand = cmd; 
      da.Fill(dt); 
      if (dt != null && dt.Rows.Count > 0 && dt.Rows[0][0].ToString().ToLower() == "exists") 
      { 
       ExistsCheck = "Exists"; 
      } 
      else 
      { 
       ExistsCheck = "Available"; 
      } 
      return View(); 
     } 
    } 

Teraz moje pytanie brzmi, jak nazwać tę SearchUser() działanie i wyświetlić go na tej samej stronie, gdy wychodzimy z textBox1.

Wszelkie sugestie proszę.

Odpowiedz

6

JavaScript

@{ 
    ViewBag.Title = "Home Page"; 
} 
@section featured { 
    <section class="featured"> 
     <div class="content-wrapper"> 
      <table> 
       <tr> 
        <td> 
         @Html.TextBox("textbox1") 
        </td> 
        <td> 
         <div id="regTitle"></div> 
        </td> 
       </tr> 
       <tr> 
        <td colspan="2"> 
         @Html.TextBox("txtTest") 
        </td> 
       </tr> 
      </table> 
     </div> 

    </section> 
} 
@section scripts{ 
<script type="text/javascript"> 
    $(document).ready(function() { 
     $('#textbox1').blur(function() { 
      var params = { userName: $(this).val() }; 
      $.ajax({ 
       url: "Home/SearchUser", 
       type: "get", 
       data: { userName: $("#textbox1").val() }, 
       success: function (response, textStatus, jqXHR) { 
        if (response.IsExisting) { 
         // User name is existing already, you can display a message to the user 
         $("#regTitle").html("Already Exists") 
        } 
        else { 
         // User name is not existing 
         $("#regTitle").html("Available") 
        } 
       }, 
       error: function (jqXHR, textStatus, errorThrown) { 
        alert("error"); 
       }, 
       // callback handler that will be called on completion 
       // which means, either on success or error 
       complete: function() { 
        } 
      }); 
     }); 
    }); 
</script> 
} 

metoda kontrolera

using System; 
using System.Collections.Generic; 
using System.Configuration; 
using System.Data; 
using System.Data.SqlClient; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 

namespace Mvc4_Ajax.Controllers 
{ 
    public class HomeController : Controller 
    { 
     public ActionResult Index() 
     { 
      ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application."; 

      return View(); 
     } 

     public ActionResult About() 
     { 
      ViewBag.Message = "Your app description page."; 

      return View(); 
     } 

     public ActionResult Contact() 
     { 
      ViewBag.Message = "Your contact page."; 

      return View(); 
     } 
     [HttpGet] 
     public ActionResult SearchUser(string userName) 
     { 
      SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["conn"].ToString()); 
      SqlDataAdapter da = new SqlDataAdapter(); 
      SqlCommand cmd = new SqlCommand(); 
      DataTable dt = new DataTable(); 
      cmd = new SqlCommand("sp_UserName_Exist_tbl_UserDetails", con); 
      cmd.CommandType = CommandType.StoredProcedure; 
      cmd.Parameters.AddWithValue("@UserName", userName); 
      da.SelectCommand = cmd; 
      da.Fill(dt); 
      var isExisting = dt != null && dt.Rows.Count > 0 && dt.Rows[0][0].ToString().ToLower() == "exists"; 
      return Json(new { IsExisting = isExisting }, JsonRequestBehavior.AllowGet);    
     } 
    } 
} 
+0

System ajax uruchamia się po raz pierwszy podczas ładowania widoku. Następnym razem ajax nie strzela. –

+0

Nie widzę * żadnego * kodu AJAX w twoim przykładzie. –

+0

Mój kod JavaScript ma zastąpić tylko 'alert (" a ");' powinieneś zachować wszystko inne. – Gabriel

2

Wymyślasz koło. MVC zapewnia interfejs - IClientValidatable - który to zapewnia. Niemal wszystkie walidacje formularzy MVC można realizować za pomocą kombinacji atrybutów właściwości (tj. [Wymagane] po stronie serwera i po stronie klienta z dyskretnym sprawdzaniem poprawności), IClientValidatable (po stronie klienta) i IValidatable (po stronie serwera). Oto pełny przykład sprawdzania poprawności - MVC3 - Custom Client-Side Validation with Unobtrusive Ajax - a Complete Example

+3

Walidacja jest tylko jednym z przykładów użycia AJAX. To jest świetne pytanie i wspaniała odpowiedź, bardzo przydatne. – Shane

Powiązane problemy