如何使用asp.net mvc5实现ajax登录?

时间:2016-03-15 18:37:06

标签: jquery ajax asp.net-mvc login

我在局部视图中有一个登录表单,它位于主模板(布局)中的模态中。单击按钮后,将显示登录表单,用户应填写该表单,直到一切正常,但每当用户单击登录按钮时,如果数据很好,则将数据发送到服务器进行验证,用户被重定向到网站安全区域,但如果没有用户丢失,因为页面已刷新并且模式未显示回来,因此用户必须单击登录以预览模式,然后查看错误!我想实现一个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>*@
        }

任何帮助将不胜感激。感谢。

Samit Patel的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);
    }
}

2 个答案:

答案 0 :(得分:4)

实际上你应该将模型来回传递给View和Controller,因此称为MVC(模型视图控制器)。我会创建一个WebLogin.cs模型,这样你就可以验证模型的状态。我对上面代码的最大问题是你包含了Anti-Forgery令牌,但你无论如何都没有处理它,这使得包含它毫无意义。

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,您可以提示用户使用等待的玻璃或旋转徽标,并在服务器端执行一些操作,并且它很干净且非常重要。

答案 1 :(得分:0)

只需点按AJAX

按钮即可发出Login个请求

首先将您的登录按钮设为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的

点击<{1}}此Jquery fire

btnSubmit

<强>控制器

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