asp.net MVC uses jquery ajax to implement Login

Source: Internet
Author: User

View [views]--login.cshtml page

<! DOCTYPE html>  

<script> $ ("#login-form"). Validate ({rules: {userName: {RE Quired:true,}, Password: {required:true, Range Length: [8]}}, messages: {userName: "Please enter a username." ", Password: {required:" Please enter a password. ", Rangelength:" Please enter the password between {0} to {1}. "}}, Submithandler:function (form) {//Get security token var token = $
                (' Input[name=__requestverificationtoken] '). Val ();
                var headers = {};
                headers["__requestverificationtoken"] = token;
                var params = $ (form). SerializeObject ();
                    $.ajax ({type: "POST", url: "Login", Data:params, Headers:headers, Success:function(Result)
                    {alert (result.msg);
                    }, Error:function () {alert ("error");
            }
                });
    }
        }); </script>


Controller [Controller]--AccountController

<pre name= "code" class= "CSharp" >using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Net;
Using System.Web.Helpers;
Using SYSTEM.WEB.MVC;

Using Mvcajaxdemo.models; Namespace Mvcajaxdemo.controllers {public class Accountcontroller:controller {////Get:/acco

            Unt/login public ActionResult Login () {viewbag.username = Retrieve ("UserName");
        return View ();
        [HttpPost] [Extendedvalidateantiforgerytoken] public actionresult Login (Logininfo model) {//whether the AJAX request if (!
            Request.isajaxrequest ()) return View (); if (model. UserName = = null) return Json (GetResult (False, "user name is empty.)
            ", null)); Gets the user var username = userservice.getusers () based on the user name. Singleordefault (p => p.loginname = = model.

            UserName); if (user = null) return Json (GetResult false, "username or passwordError.
            ", null)); Verify password if (user. Password!= model. Password return Json (False, GetResult username or password error.)

            ", null)); if (!string. Isnullorwhitespace (model. RememberMe) {//Save account Login name Save ("UserName", model.
            UserName, DateTime.Now.AddDays (2)); Return Json (GetResult false, "login succeeded.)

        ", null)); #region Helper Methods///<summary>///get result set///</summary>///<param N Ame= "rel" > Status </param>///<param name= "MSG" > Hint information </param>///<param name= "Data" >  Data set </param>///<returns></returns> public static object GetResult (bool rel, String msg,  Object Data {return new dictionary<string, object> {"rel", rel}, {"Msg", msg}, {"Obj",
        Data}};
    }///<summary>///save Cookie///</summary>    <param name= "key" > Key </param>///<param name= "value" > Value </param>///<para
            M name= "expires" > Expiration </param> public void Save (string key, String value, DateTime expires) {
            var HttpCookie = System.web.httpcontext.current.response.cookies[key];
            if (HttpCookie = null) return;
            Httpcookie.value = Value;
        Httpcookie.expires = Expires; ///<summary>///Retrieves cookies///</summary>///<param name= "key" > Key </  param>///<returns></returns> public string Retrieve (string key) {var
            cookie = System.web.httpcontext.current.request.cookies[key]; Return cookie!= null? Cookie.
        Value: "";
    #endregion} #region Prevent csrf attack characteristics///<summary>///prevent csrf attack characteristics///</summary> public class Extendedvalidateantiforgerytoken:autHorizeattribute {public override void Onauthorization (AuthorizationContext filtercontext) {
            var request = FilterContext.HttpContext.Request; if (request).
            HttpMethod!= WebRequestMethods.Http.Post) return; if (request). Isajaxrequest ()) {var Antiforgerycookie = Request.
                Cookies[antiforgeryconfig.cookiename]; var cookievalue = Antiforgerycookie!= null?
                AntiForgeryCookie.Value:null; Verify the anti-counterfeiting mark from cookies and Headers//Here you can add Try-catch antiforgery.validate (Cookievalue, Request.H
            eaders["__requestverificationtoken"]); else {new Validateantiforgerytokenattribute ().
            Onauthorization (Filtercontext);
        #endregion//model public class User {public int Id {get; set;}
        public string LoginName {get; set;} public string Password {get; Set
            } public class UserService {public static ilist<user> getusers () {
                    return new List<user> {new User {id=1,
                LoginName = "Admin", Password = "admin1234"}, New User
                {id=2, LoginName = "Demo", Password = "demo1234" }, new User {id=3, LoginName = "Te
        St ", Password =" test1234 "},};
 }
    }
}


Model [Models]--LoginInfo.cs

Namespace Mvcajaxdemo.models
{public
    class Logininfo
    {
        ///<summary>
        ///user name
        ///< /summary> public
        string UserName {get; set;}
        <summary>
        ///Password
        ///</summary> public
        string Password {get; set;}
        <summary>
        ///Remember me.
        ///</summary> Public
        string RememberMe {get; set;}
    }
}


Effect Chart:



Demo Download address Http://yunpan.cn/c3bQqR9NzsH8Q access password 6683


If you have any questions, you can leave a message for me.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.