Tuesday, 23 September 2014

Ajax Login Form Using jQuery in Asp.net MVC and C#.Net

9/23/2014 - By Pranav Singh 6

This article will show you how you can create an ajax enabled login for in asp.net mvc using jQuery and c#.net.  This will help you validating user without refresh of the page. This article you can use in MVC2,  MVC3, MVC4, MVC5.


So for this article first we will create a new asp.net mvc application and add the model class file in our mode folder. After adding model class file we will add the below code into our class file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcApplication1.Models
{
    public class UserLoginModel
    {
        public List<UserDetail> UserDetailList { get; set; }
    }
    public class UserDetail
    {
        public string UserId { get; set; }
        public string Password { get; set; }
    }
}

Now we will add a new controller class file in our controller folder and add the below code into the controller class file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;

namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }
        public string ValidateUser(string userId, string pass)
        {
            /*Replace this query of code with you DB code.*/
            var uservalidation = (from data in GetDataFromDB()
                                  where data.UserId == userId && data.Password == pass
                                  select data).FirstOrDefault();
            if (uservalidation != null)
            {
                return "1";
            }
            else
            {
                return "0";
            }
        }
        ///
        /// This function will return data collection
        /// ///
        private List<UserDetail> GetDataFromDB()
        {
            List<UserDetail> objUserDetail = new List<UserDetail>();
            objUserDetail.Add(new UserDetail { UserId = "user1", Password = "pass1" });
            objUserDetail.Add(new UserDetail { UserId = "user2", Password = "pass2" });
            objUserDetail.Add(new UserDetail { UserId = "user3", Password = "pass3" });
            objUserDetail.Add(new UserDetail { UserId = "user4", Password = "pass4" });
            objUserDetail.Add(new UserDetail { UserId = "user5", Password = "pass5" });
            return objUserDetail;
        }
    }
}

       
In above code I have created  a static data for validating user from this list.  Now check the ValidateUser function whose return type is string in this I have written a linq query for validating user detail. You just replace the GetDataFromDB() function with the entity table from which you want to validate the detail.

Now generate the view and add the below code into it.

@model MvcApplication1.Models.UserDetail
@{
    ViewBag.Title = "Ajax Login Form Using jQuery in Asp.net MVC and C#.Net";
}
<script src="../../Scripts/jquery.js" type="text/javascript"></script>
<script language="javascript">
    function ValidateUser() {
        var userid = $("#txtuserid").attr('value');
        var password = $("#txtpassword").attr('value');
        var url = "/Home/ValidateUser/";
        $("#btnlogin").val('Plesae wait..');
        $.ajax({
            url: url,
            data: { userId: userid, pass: password },
            cache: false,
            type: "POST",
            success: function (data) {
                if (data == "1") {
                    alert("Successfull login.");
                } else {
                    alert("Invalid user id and password.");
                }
                $("#txtuserid").attr({ 'value': '' });
                $("#txtpassword").attr({ 'value': '' });
            },
            error: function (reponse) {
                alert("error : " + reponse);
            }
        });
        $("#btnlogin").val('Login');
    }
</script>
@using (Html.BeginForm("Index", "Home"))
{
    <table width="100%" cellpadding="5" cellspacing="0" border="1">
        <tr>
            <td align="right">
                User Id :
            </td>
            <td align="left">@Html.TextBoxFor(m => m.UserId, new { @id = "txtuserid" })
            </td>
        </tr>
        <tr>
            <td align="right">
                Password :
            </td>
            <td align="left">@Html.PasswordFor(m => m.Password, new { @id = "txtpassword" })
            </td>
        </tr>
        <tr>
            <td align="center" colspan="2">
                <input type="button" value="Login" id="btnlogin" onclick="javascript:ValidateUser();" />
            </td>
        </tr>
    </table>
   
}

In above code I have written a jQuery code. In which I have used a jQuery ajax function to validate the user.  In this Ajax function in passed URL I have passed the controller name and the method name whose return type is string. In ValidateUser function passed parameter name is same as the passed parameter value in Ajax function.

So we have done run the application to check the output.


About the Author

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Get Updates

Subscribe to our e-mail newsletter to receive updates.

Share This Post

6 comments:

  1. What is data and GetDataFromDB here would you please explain ???

    ReplyDelete
  2. What is data and GetDataFromDB here would you please explain ???

    ReplyDelete
    Replies
    1. This is the function which is having data source. Toy can use entity table object.

      Delete

Please let me know your view

Free Ebooks


About Us

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Contact Us

For writing article in this website please send request by your

GMAIL ID: dotnetpools@gmail.com

Bugs and Suggestions

As we all know that this website is for sharing knowledge and providing proper solution. So while reading the article is you find any bug or if you have any suggestion please mail us at contact@aspdotnet-pools.com.

Partners


Global Classified : Connectseekers.com
© 2014 aspdotnet-pools.com Designed by Bloggertheme9.
back to top