2013-12-12 68 views
3

以下工作,但是如何將其轉換爲Ajax調用?如何將Html.BeginForm轉換爲Ajax.BeginForm

<section id="loginWindow"> 
@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl })) { 
@Html.AntiForgeryToken() 
@Html.ValidationSummary(true) 

<fieldset> 
    <legend>Log in Form</legend> 
    <ol> 
     <li> 
      @Html.LabelFor(m => m.UserName) 
      @Html.TextBoxFor(m => m.UserName) 
      @Html.ValidationMessageFor(m => m.UserName) 
     </li> 
     <li> 
      @Html.LabelFor(m => m.Password) 
      @Html.PasswordFor(m => m.Password) 
      @Html.ValidationMessageFor(m => m.Password) 
     </li> 
     <li> 
      @Html.CheckBoxFor(m => m.RememberMe) 
      @Html.LabelFor(m => m.RememberMe, new { @class = "checkbox" }) 
     </li> 
    </ol> 
    <input type="submit" value="Log in" /> 
</fieldset> 

} 
</section> 
+1

你檢查了[這個答案](http://stackoverflow.com/a/5410121/1831275)? – albusshin

回答

5

您的形式改成這樣:

@using (Ajax.BeginForm("Login", "Account", new AjaxOptions { OnSuccess = "onSuccess" })) 
{ 
    @Html.AntiForgeryToken() 
    @Html.ValidationSummary(true) 

    <fieldset> 
     <legend>Log in Form</legend> 
     <ol> 
      <li> 
       @Html.LabelFor(m => m.UserName) 
       @Html.TextBoxFor(m => m.UserName) 
       @Html.ValidationMessageFor(m => m.UserName) 
      </li> 
      <li> 
       @Html.LabelFor(m => m.Password) 
       @Html.PasswordFor(m => m.Password) 
       @Html.ValidationMessageFor(m => m.Password) 
      </li> 
      <li> 
       @Html.CheckBoxFor(m => m.RememberMe) 
       @Html.LabelFor(m => m.RememberMe, new { @class = "checkbox" }) 
      </li> 
     </ol> 
     <input type="submit" value="Log in" /> 
    </fieldset> 
} 

確保您的登錄操作返回重定向的URL,在成功登錄的情況下,這個腳本添加到您的視圖:

<script type="text/javascript"> 
    function onSuccess(result) { 
     if(result.url) { 
      window.location.href = result.url; 
     } 
    } 
</script> 
相關問題