Home > DeveloperSection > Blogs > Implement Ajax Login in ASP.NET MVC

Implement Ajax Login in ASP.NET MVC


AJAX AJAX  Mvc4  Ajax.net 
Ratings:
0 Comment(s)
 5275  View(s)
Rate this:

Implement Ajax Login in ASP.NET MVC


Hi everyone in this blog I’m explaining about Ajax login in Asp.net MVC.

Description:


In this blog I’m demonstrate how Ajax login can be implemented using jQuery $.ajax (). Implementing Ajax based login involves many of the same steps as the normal forms authentication. However, the login page doesn't send user ID and password to the server through a standard form submission. Instead, user credentials are sent to the server via an Ajax request. The credentials are then validated on the server and the result of the verification process is conveyed to the client. If the login attempt was successful, the user is taken to the secured area of the website.


Let's understand how all this works by developing a sample application. Begin by creating a new ASP.NET MVC Web Application using an empty template. To keep things simple we will add only those things to the project that are absolutely essential to the functioning of this example.


Step 1:  Open visual studio >> File >> New Project >> ASP.NET MVC Web Application

Give the application name in my sample Name “LoginManage” and click ok.

After click ok open a window and you select project type in this sample I have select “Empty” template.

Now our application is stand successfully.

Step 2:  Now we have make database and table

CREATE TABLE Login

(

                Id INT IDENTITY(1,1)PRIMARY KEY,

                Name VARCHAR(100),

                Password VARCHAR(20)

)

 

And insert some dummy data in this table.

Step 3:  Now our need to configure database. This is done with help of .edmx file for use code first approach. Learn more about Code first Approach.

 

Step 4: Create Account Controller and Login View

Then add a controller to the Controllers folder - AccountController. The Account controller contains code that validates a user. The Login () and ValidateUser () action methods of the Account controller are shown below:

 

AccountController:

 

public class AccountController : Controller

    {

        //

        // GET: /Account/

 

        MyDBEntities db = new MyDBEntities();

 

        public ActionResult Login()

        {

            return View();

        }

        [HttpPost]

        public JsonResult ValidateUser(string userid, string password)

        {

            var data = from c in db.Logins where c.Name == userid && c.Password == password select c;

            if (data.Count()>0)

                return Json(new { Success = true }, JsonRequestBehavior.AllowGet);

            else

                return Json(new { Success = false }, JsonRequestBehavior.AllowGet);

        }

    }

 

The Login () action method simply returns the Login view. The ValidateUser () method is important to us because this method validates the user credentials and is called via Ajax. The ValidateUser () method takes two parameter – userid and password. Inside, inside ValidateUser () method execute a query for user is validate or not correct. The Login class looks like this:

public partial class Login

{

        public int Id { get; set; }

        public string Name { get; set; }

        public string Password { get; set; }

 }

 

The Login class consists of three properties - Id, Name and Password. The Id property holds user id that is unique. The Name property holds a Username. The password property holds the user password.

 

Login View:

 

<div class="container">

    <div class="row">

        <div class="col-md-6 col-md-offset-3 alert alert-warning">

            <h2 class="text-center">Login</h2>

            <div class="row">

                <div class="col-md-12">

                    <div class="form-group">

                        <div class="input-group">

                            <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>

                            <input type="text" id="userid" class="form-control" placeholder="Username">

                        </div>

                    </div>

                </div>

            </div>

            <div class="row">

                <div class="col-md-12">

                    <div class="form-group">

                        <div class="input-group">

                            <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>

                            <input type="password" class="form-control" id="password" placeholder="Password">

                        </div>

                    </div>

                </div>

            </div>

            <div class="row">

                <div class="col-md-12">

                    <div class="form-group">

                        <button class="btn btn-warning form-control" type="submit" id="savedata"><i class="glyphicon glyphicon-log-in"></i>&nbsp;Login</button>

                    </div>

                </div>

            </div>

        </div>

    </div>

</div>

 

 

The Login view consists of a textbox, a password box and a button. Clicking on the Login button initiates an Ajax request to the ValidateUser () method you created earlier. The jQuery code responsible for calling the ValidateUser () method is given below:

 

<script>

    $(document).ready(function () {

        $('#savedata').click(function () {

            var data = {

                "userid": $("#userid").val(),

                "password": $("#password").val()

            };

            $.ajax({

                url: "/Account/validateuser",

                type: "POST",

                data: JSON.stringify(data),

                dataType: "json",

                contentType: "application/json",

                success: function (response) {

                    if (response.Success) {

                        $.get("@Url.Action("Index", "Home")", function (data) {

                            $('.container').html(data);

                        });

                      

                    }

                    else

                        window.location.href = "@Url.Action("Login", "Account")";

                },

                error: function () {

                    console.log('Login Fail!!!');

                }

            });

        });

    });

</script>

 

The code then forms a JavaScript object that has three properties – userid and password. These property names must match the parameter names of the ValidateUser () action method you created earlier. Then $.ajax () of jQuery is used to make an Ajax request to /account/validateuser. The type of the request is set to POST. The data setting contains the stringified version of the data JavaScript object you just created. The dataType and contentType properties are set to json and application/json respectively. These two properties represent the response format and the request MIME content type respectively. The success function receives a status object. This object is a JSON representation of Login object you return from the ValidateUser () method. If the Success property is true it means that the login attempt was successful and the user is redirected to the Home Controller using window.location.href property. If the login attempt fails that time user redirect Account Controller Login Action. The error function is invoked if there is any error making the Ajax call and simply displays an error message to the user.

The following figure shows the login view in action:

 

 

Step 5:  Create Home controller and Index view

 

If a login attempt is successful the user is taken to the Index view. So, add the Home controller and also the Index view.

 

public class HomeController : Controller

{

        //

        // GET: /Home/

 

        public ActionResult Index()

        {

            return View();

        }

 }

 

The index view contains simply welcome message.

 

@{

    ViewBag.Title = "Index";

}

 

<h2>Welcome in Index Methods</h2>

 


in my next post i'll explain about Render Partial Views in ASP.NET MVC Using Ajax


Don't want to miss updates? Please click the below button!

Follow MindStick