2016-03-15 48 views
0

我在一個局部視圖中有一個登錄表單,它位於主模板(佈局)中的模式中。點擊一個按鈕後,登錄表單出現,用戶應該填寫該表單,直到一切都很好,但無論何時用戶單擊登錄按鈕,數據都會發送到服務器進行驗證,如果數據沒有問題,用戶將被重定向到網站的安全區域,但如果不是用戶丟失,因爲頁面已刷新,模式不顯示,所以用戶不得不點擊登錄預覽模式,然後看到錯誤!我想實現一個ajax登錄,當用戶點擊登錄按鈕時,如果數據是正確的,應該重定向到網站安全區域,否則應該給出錯誤。這是登錄的局部視圖。我如何實現與asp.net mvc5的ajax登錄?

@model Hire.af.WebUI.Models.LoginViewModel 



    <!--Login Form--> 
     @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "noo-ajax-login-form form-horizontal", role = "form" })) 
     { 
      @Html.AntiForgeryToken() 
      <hr /> 
      @Html.ValidationSummary(true, "", new { @class = "text-danger" }) 
      <div class="form-group row"> 
       <div class="col-sm-9"> 
        @Html.TextBoxFor(m => m.Email, new { @class = "log form-control", @placeholder="Email OR Username" }) 
        @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" }) 
       </div> 
      </div> 
      <div class="form-group row"> 
       @Html.LabelFor(m => m.Password, new { @class = "col-sm-3 control-label" }) 
       <div class="col-sm-9"> 
        @Html.PasswordFor(m => m.Password, new { @class = "pwd form-control", @placeholder="Password" }) 
        @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" }) 
       </div> 
      </div> 
      <div class="form-group row"> 
       <div class="col-sm-9 col-sm-offset-3"> 
        <div class="checkbox"> 
         <div class="form-control-flat"> 
          <label class="checkbox"> 
           @Html.CheckBoxFor(m => m.RememberMe, new { @class = "rememberme", @type = "checkbox" }) 
           <i></i> Remember Me 
          </label> 
         </div> 
        </div> 
       </div> 
      </div> 

      <!--Remember Me Checkbox--> 
       <div class="form-actions form-group text-center"> 
        <input type="submit" value="Sign In" class="btn btn-primary" /> 
        <div class="login-form-links"> 
         <span><a href="#"><i class="fa fa-question-circle"></i> Forgot Password?</a></span> 
         <span> 
          Don't have an account yet? 
          <a href="#" class="member-register-link" data-rel="registerModal"> 
           @Html.ActionLink("Register Now", "Register") <i class="fa fa-long-arrow-right"></i> 
          </a> 
         </span> 
        </div> 
       </div> 

      @* Enable this once you have account confirmation enabled for password reset functionality 
      <p> 
       @Html.ActionLink("Forgot your password?", "ForgotPassword") 
      </p>*@ 
     } 

任何幫助,將不勝感激。謝謝。

EDIT1的薩米特帕特爾:這裏是登錄

控制器的操作方法
// GET: /Account/Login 
[AllowAnonymous] 
public ActionResult Login(string returnUrl) 
{ 
    ViewBag.ReturnUrl = returnUrl; 
    return View(); 
} 
// 
// POST: /Account/Login 
[HttpPost] 
[AllowAnonymous] 
[ValidateAntiForgeryToken] 
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) 
{ 
    if (!ModelState.IsValid) 
    { 
     return View(model); 
    } 

    // This doesn't count login failures towards account lockout 
    // To enable password failures to trigger account lockout, change to shouldLockout: true 
    var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false); 
    switch (result) 
    { 
     case SignInStatus.Success: 
      return RedirectToLocal(returnUrl); 
     case SignInStatus.LockedOut: 
      return View("Lockout"); 
     case SignInStatus.RequiresVerification: 
      return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); 
     case SignInStatus.Failure: 
     default: 
      ModelState.AddModelError("", "Invalid login attempt."); 
      return View(model); 
    } 
} 
+0

真正的問題是爲什麼你會這樣做。登錄是每會話一次的動作,所以你的每個頁面現在都被髮送,並且呈現,大部分額外的html將不會被99%的時間需要。只需按照[Authorize]標記適當方法的正常模式,如果用戶導航到它,它們將被重定向到您的登錄頁面,如果成功,則導航到它們正在導航的頁面。 –

+0

@StephenMuecke你能先請讀一下這個問題嗎?這個問題與你的評論無關。我想實現ajax登錄 –

+0

我確切地知道你想做什麼!我在質疑爲什麼在佈局中不必要地包含登錄表單的html,而不是僅在需要時動態加載它。而且ajax的全部目的是保持在同一頁面上,所以'return RedirectToAction()'是毫無意義的,因爲ajax調用永遠不會重定向。 –

回答

0

只是要對Login按鈕點擊AJAX要求,

首先讓你的登錄按鈕Button型,

分配ID到窗體

@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "noo-ajax-login-form form-horizontal", role = "form" , @id = "yourID" })) 
    { 
} 

HTML

<input type="button" id="btnSubmit"/> 

jQuery的

btnSubmit點擊這個jQuery火

$("#btnSubmit").click(function) 
    { 
     $,ajax({ 
      url:"Account/Login?Username=" + username + "&pass=" + pass, 
      success: function(result) 
       { 
        if(result == "Authenticated") 
        { 
         $("#yourID").submit(); 
        } 
        else 
        { 
         alert("Login Failed"); 
        } 
        } 
     }) 
    } 

控制器

+0

感謝您的答覆,似乎我仍然需要做很多,只要我是新的ajax和mvc你能讓我的問題更清楚一點嗎?如果您需要我提供控制器操作,請讓我知道 –

+0

是請提供控制器的操作方法 –

+0

謝謝,請參閱最新的問題。 –

2

真的,你應該傳遞模型來回的視圖和控制器,因此被稱爲MVC(模型 - 視圖 - 控制器)。我會創建一個WebLogin.cs模型,這樣你可以驗證模型的狀態。我在上面的代碼中遇到的最大問題是您包含了反僞造令牌,但是您無法處理它,因此無法包含它。

WebLogin {

[Required] 
public string Name {get;set;} 
[Required] 
public string Password {get;set;} 
} 

在這裏可以允許HTML,預設的字符串和噸的最大長度更通過數據註釋和設置一些預定的錯誤消息,以引導用戶在發生錯誤的情況下。

請參閱以下內容: https://msdn.microsoft.com/en-us/library/ee256141(v=vs.100).aspx

控制器側:

[HttpGet] 
public async Task<ActionResult> AuthenticateUser(){ 
return View(new WebLoginModel()); 
} 

[HttpPost,ValidateAntiforgeryToken] 
public async Task<ActionResult> AuthenticateUser(WebLoginModel login){ 
//Right here you can flag a model is invalid and return an error to the Jquery 
//AJAX call and handle it directly with HTML. 
if(!ModelState.Valid)return new HttpStatusCodeResult(HttpstatusCode.Invalid); 
    var validLogin = LoginMethodInYourModel(Or whatever else you are using). 
} 

在HTML/jQuery的你會做這樣的:

<script type="text/javascript"> 
    $('form').submit(function() { 
     var form = $('form'); // This will work if its the only form in the     
     //view, otherwise use an Id, Name or even a class will work. 
     var token = $('input[name="__RequestVerificationToken"]', form).val(); 
     var lData = $('form').serialize(); 
     $.ajax({ 
      url: $(this).data('url'), 
      type: 'POST', 
      data: { 
       __RequestVerificationToken: token, 
       WebLoginModel: lData 
      }, 
      success: function (result) { 
       alert(result.someValue); 
      }, 
      error:function(errorResult){ 
       //You can handle the error gracefully here and allow your user to 
       //know what is going on. 
      } 
     }); 
     return false; 
    }); 
</script> 

我不能把所有的爲此,我實際上學會了處理/驗證來自以下帖子的反僞造令牌的最佳方式:

include antiforgerytoken in ajax post ASP.NET MVC

通過使用jQuery做這種方式可以提示一個等待玻璃或旋轉標識用戶,做服務器端的一些工作,它是乾淨的,給點意見。