2017-03-07 70 views
-2

我想調用api,做數據庫的客戶登錄檢查,如果登錄成功,它將返回與此警報,我也適用dataAnnotation在該模型。MVC 4/C#:ModelState.IsValid爲真時運行ajax調用

public class Customers 
{ 
    public int Id { get; set; } 

    [Required(ErrorMessage = "Please Enter Customer's Name")] 
    [StringLength(255)] 
    public String Name { get; set; } 

    [Display(Name = "Date Of Birth")] 
    public DateTime? BirthDate { get; set; } 

    [Required] 
    [StringLength(255)] 
    public string Password { get; set; } 
} 

這是我使用的視圖:

@model CodeFirstCustomers.ViewModel.CustomerViewModel 
@using (Html.BeginForm("LoginProcess", "Login")) 
{ 
    <div class="container"> 
     <div class="row"> 
      <div class="col-md-6 col-md-offset-3 alert alert-warning"> 
       <div class="row"> 
        <div class="col-md-12"> 
         <div class="form-group"> 
          @Html.LabelFor(c => c.Customers.Name) 
          @Html.TextBoxFor(c=>c.Customers.Name,new { @class="form-control"}) 
          @Html.ValidationMessageFor(c=>c.Customers.Name) 
         </div> 
         <div class="form-group"> 
          @Html.LabelFor(c => c.Customers.Password) 
          @Html.TextBoxFor(c => c.Customers.Password, new { @class = "form-control" }) 
          @Html.ValidationMessageFor(c => c.Customers.Password) 
         </div> 
         @Html.AntiForgeryToken() 
         <button value="Submit" class="btn btn-primary">Save</button> 
        </div> 
       </div> 


      </div> 
     </div> 
     </div> 

這是AJAX調用,網址是一個API,將客戶作爲參數,然後檢查用戶名和密碼是真的,那將返回好的或沒有找到。

@section scripts{ 
      <script> 
       $(document).ready(function() { 

        $("#savedata").on("click", function (evt) { 
         evt.preventDefault(); 
         // var form = $("form"); 

         if ($(form).valid()) { 
          var data = { 
           Name: $("#userid").val(), 
           Password: $("#password").val() 
          } 
          $.ajax({ 

           url: "/api/login", 
           type: "POST", 
           data: JSON.stringify(data), 
           contentType: "application/json", 
           success: function() { 
            alert("Success"); 

           }, 
           error: function() { 
            alert("Fail"); 
           } 
          });//Ajax call 

         } 
         else { 
          return false; 
         } 
        });//savedata 
       }); 
      </script> 

     } 

這是將執行檢查的API:

public class LoginController : ApiController 
    { 
     private ApplicationDbContext _context; 
     public LoginController() 
     { 
      _context = new ApplicationDbContext(); 
     } 
     //POST: api/login 
     [System.Web.Mvc.HttpPost] 
     public IHttpActionResult ValidateCustomer(Customers customer) 
     { 
      if(!ModelState.IsValid) 
      { 
       return BadRequest(); 
      } 
      var checks = _context.Customers.SingleOrDefault(c => c.Name == customer.Name && c.Password == customer.Password); 
      if (checks == null) 
      { 
       return NotFound(); 
      } 
      else 
      { 

       return Ok(); 
      } 

     } 
    } 

,這是LoginProcess行動:

[HttpPost] 
    [ValidateAntiForgeryToken] 
    public ActionResult LoginProcess(Customers customers) 
    { 
     if (!ModelState.IsValid) 
     { 
      var viewModel = new CustomerViewModel 
      { 
       Customers = customers 

      }; 
      return View("loginPage", viewModel); 
     } 
     else 
     { 
      return RedirectToAction("Index", "Home"); 
     } 
    } 

API登錄:

public class LoginValidationController : ApiController 
    { 
     private ApplicationDbContext _context; 
     public LoginValidationController() 
     { 
      _context = new ApplicationDbContext(); 
     } 

     [HttpPost] 
     public IHttpActionResult ValidateCustomer(Customers customer) 
     { 
      if (!ModelState.IsValid) 
      { 
       return BadRequest(); 
      } 
      var checks = _context.Customers.SingleOrDefault(c => c.Name == customer.Name && c.Password == customer.Password); 
      if (checks == null) 
      { 
       return NotFound(); 
      } 
      else 
      { 

       return Ok(); 
      } 

     } 

    } 

the is validation is working perfectly, but how can i execute the ajax code 

後驗證使用modelS成功tate.IsValid?

+0

你想執行一個腳本,當它從「LoginProcess」動作重定向到「Home」控制器上的「索引」操作時 – RonyLoud

+0

@RonyLoud簡單地說,我想在檢查ModelState和腳本成功之後運行腳本想要重定向到索引,登錄檢查本質上是由ajax調用 –

+0

如果你想在第一個返回OK後調用「LoginProcess」方法,那麼你可以在第一個Ajax調用的成功中有另一個Ajax調用 –

回答

0

理想情況下,您不需要登錄頁面中的Ajax。只需添加type="submit"按鈕

如果你能使它工作,你可以在以後使用Ajax。

@model CodeFirstCustomers.ViewModel.CustomerViewModel 
@using (Html.BeginForm("LoginProcess", "Login")) 
{ 
    <div class="container"> 
     <div class="row"> 
      <div class="col-md-6 col-md-offset-3 alert alert-warning"> 
       <div class="row"> 
        <div class="col-md-12"> 
         ... 
         <button type="submit" class="btn btn-primary">Save</button> 
        </div> 
       </div> 
      </div> 
     </div> 
    </div> 
} 

[HttpPost] 
[AllowAnonymous] 
[ValidateAntiForgeryToken] 
public ActionResult Login(CustomerViewModel model) 
{ 
    if (ModelState.IsValid) 
    { 
     // Validate crendential here. If valid user, return to Home. 
     if (true) 
     { 
      return RedirectToAction("Index", "Home"); 
     } 
     ModelState.AddModelError("", "Incorrect username or password."); 
    } 
    return View(model); 
} 

您可以查看登錄頁面示例代碼my GitHub project

+0

但我需要ajax調用api才能驗證api中的crendential。 –

+0

在您的場景中,在登錄頁面進行Ajax調用沒有任何意義,因爲除非您正在開發真正的SPA網站,否則無論如何您都將用戶重定向到新頁面。 – Win

+0

好的,處理...如果我驗證api中的憑證,那麼在成功時,我將用戶重定向到另一個頁面,使用我解決了我的問題,但是如果用戶沒有輸入密碼或用戶名,客戶端驗證如何? –

相關問題