2015-04-24 84 views
9

我有一個帳戶控制器,我想當我輸入一個不正確的模式引導用戶名/密碼它會返回一條消息「無效的登錄嘗試。」從ActionResult Login()到模態。如何從服務器端驗證模態引導?

我_loginPartialView:

<div id="loginModal" class="modal fade"> 
<div class="modal-dialog"> 
    <div class="modal-content"> 
     <div class="modal-header"> 
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> 
      <h4 class="modal-title">Login</h4> 
     </div> 
     <div class="modal-body"> 
      <section id="loginForm"> 
       @using (Ajax.BeginForm("Login", "Account", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "loginModal" })) 
       { 
        @Html.AntiForgeryToken() 
        @Html.ValidationSummary(true, "", new { @class = "text-danger" }) 
        <div class="form-group"> 
         @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" }) 
         <div class="col-md-10"> 
          @Html.TextBoxFor(m => m.Email, new { @class = "form-control" }) 
          @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" }) 
         </div> 
        </div> 
        <div class="form-group"> 
         @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" }) 
         <div class="col-md-10"> 
          @Html.PasswordFor(m => m.Password, new { @class = "form-control" }) 
          @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" }) 
         </div> 
        </div> 
        <div style="text-align:right;"> 
         <button type="submit" class="btn btn-primary btn-sm">Submmit</button> 
        </div> 
       } 

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

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> 
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> 

<script> 
    $(document).ready(function() { 
     $('.launchLoginModal').click(function() { 
      $('#loginModal').modal({ 
       keyboard: false 
      }); 
     }); 
    }); 
</script> 

我的控制器:

[HttpPost] 
    [AllowAnonymous] 
    [ValidateAntiForgeryToken] 
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) 
    { 
     var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false); 
     switch (result) 
     { 
      case SignInStatus.Failure: 
      default: 
       ModelState.AddModelError("", "Invalid login attempt."); 
       return PartialView("_LoginModalPartial", model); 
     } 
    } 
+0

你有沒有考慮過使用Ajax.BeginForm,然後返回你的部分模態視圖進入頁面。 –

+0

@Symeon我嘗試過使用Ajax.BeginForm並返回控制器中的PartialView,但是當我submmited它重定向到https:// localhost:xxxxx/Account/Login並呈現部分視圖。不顯示模式對話框。我不想重定向到另一個視圖 –

+0

聽起來像登錄失敗,或者登錄方法不允許匿名 - 儘管您的頂部有[AllowAnonymous]標記。你有沒有在調試中試過它,看看它是否進入了Login方法? –

回答

0

我加了這個評論,但它可以幫助作爲解決方案。這聽起來像表單提交的無效輸入導致與空白頁上的模態內容重定向?由於模式是局部視圖,因此請嘗試將腳本移動到_loginPartialView的頂部。對於您在佈局頁面中使用的任何軟件包也可能適用。

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> 
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> 
<div id="loginModal" class="modal fade"> 
     ... 
</div> 
0
  • 首先,由於您使用的@Ajax助手,你應該安裝和參考微軟jQuery的不顯眼的Ajax(你可以在這裏找到一個較舊的,但仍然中肯指南:https://www.asp.net/mvc/overview/older-versions/creating-a-mvc-3-application-with-razor-and-unobtrusive-javascript)。

  • 其次,你應該啓用客戶端驗證(見指南)

  • 第三,你需要指定現有的DOM元素進行更新UpdateTargetId(我沒有看到「loginModal」在代碼示例)。我相信這個id應該在模態html代碼中,否則它會重新創建模態html並重置其狀態。 (我會在父視圖中移動模態定義,並讓部分僅使用表單定義)。

0

一般:

  1. 修改你的控制器返回登錄嘗試的JSON結果
  2. 製作提交按鈕,它定期按鈕,它實際上並沒有提交。
  3. 使用jQuery建立一個JSON對象
  4. 使用jQuery的職位,JSON對象到控制器
  5. 在你的AJAX,檢查控制器返回並採取相應行動
  6. 添加一小格的用戶反饋
  7. 刪除ModelState.AddModelError("", "Invalid login attempt.");
  8. 在您的控制器中,嘗試/抓住您的邏輯,以便始終將JSON返回給模態的ajax。在那裏處理錯誤(見下文)

(顯然,你可以使用任何選擇的單詞,如'成功'或其他。)

你的剃鬚刀可能類似於:

// on login button click 
    $('#btnSubmit').on('click', function() { 
     $("#loginForm").validate(); // using jqueryvalidate 
     if ($('#loginForm').valid()){      // if valid, submit 
      // Get values from Modal and put into JSON object mimicking correct model 
     var token = $('input[name="__RequestVerificationToken"]').val(); // this is required for the anti-forgery decoration and must be structured outside the model to be submitted 
     var model = { 
      Email: $('#Email').val(), 
      Password: $('#Password').val() 
      }; 
     var ajaxData = { 
      __RequestVerificationToken: token, 
      model: model 
     } 
      // send 
     $.ajax({ 
      type: "GET", 
      url: '@Url.Action("method", "controller")', 
      data: ajaxData, 
      success: function (msg) { 
       // ajax success, but see if the login was a success 
       if (msg.IsError == 'true'{ all good} 
       else { 
         if (msg.Message != 'success'){ 
          $('#UserFeedback').val('Invalid Login') 
         } 
         } 
      }, 
      error: function(XMLHttpRequest, textStatus, errorThrown) { 
       console.info(errorThrown); 
       // userfeedback 
       $('#UserFeedback').html(errorThrown); 

       }); 
      } 
     }); 
     } 
    }); 

你的控制器可以返回一個自定義的視圖模型,如:

public class LoginCheckViewModel 
{  
    [DisplayName("IsError")] 
    public string IsError {get; set;} 

    [DisplayName("Message")] 
    public string Message { get; set; }   
} 

您控制器將檢查登錄,你有,但隨後返回

myLoginCheckViewModel = new LoginCheckViewModel(); 
myLoginCheckViewModel.IsError = [true/false]; 
myLoginCheckViewModel.Message = [success/fail]; 
return Json(myLoginCheckViewModel, JsonRequestBehavior.AllowGet);