Sunday, 2 January 2022

Asp.net Core 6: Ajax Login Form Using jQuery, C# Validate From Ms Sql Server Database

1/02/2022 - By Pranav Singh 0

In this article I will show you how you can create an ajax login form to validate user login detail from database table using jQuery in your asp.net core 6 application using c#.net. In ajax login form user validation from database in asp.net core 6 without refreshing the page using jQuery.

Now for this asp.net core 6 login example we will first create an asp.net core project and install Microsoft.EntityFrameworkCore.SqlServer and Microsoft.EntityFrameworkCore.Tools nuget package, after installing this we will run Scaffold-DbContext to make the connection using entity framework.


To know How To Connect MS SQL Server Database in Asp.netCore MVC Using C#.Net just click on the click.


Now we will create a sql table which having user login detail.



After this we will create the Model class file, and add the below code.


using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

 

namespace LoginProject.Models

{

    public class LoginModel

    {

        public string LoginId { get; set; }

        public string Password { get; set; }

    }

}



After his we will open the controller class file and add the below httpget code in it.


  [HttpGet]

        public IActionResult LoginIndex()

        {

            LoginModel loginModel = new LoginModel();

            return View(loginModel);

        }



Now we will create the view for the login page and add the below code in it.


@model LoginProject.Models.LoginModel

 

@{

    ViewBag.Title = "Ajax Login form";

}

 

@using (Html.BeginForm("LoginIndex", "Home", FormMethod.Post, new { @Id = "formlogin" }))

{

    <div style="font-weight:bold; font-size:16px; color:red;" id="divmessage"></div>

    <div>

        <h2>User Registration</h2>

        <div class="row">

            <div class="form-group col-6">

                <lable for="loginid">Login Id</lable>

                @Html.TextBoxFor(m => m.LoginId, new { @class = "form-control", @placeholder = "Enter login id" })

            </div>

        </div>

        <div class="row">

            <div class="form-group col-6">

                <lable for="loginid">Password</lable>

                @Html.PasswordFor(m => m.Password, new { @class = "form-control", @placeholder = "Enter password" })

            </div>

        </div>

        <div class="row">

            <div class="form-group col-12">

                <input type="button" value="Login" onclick="javascript: UserLoginValudation();" id="btnLogin" />

            </div>

        </div>

    </div>

}



In above code check the highlighted par of code. This is the client side script function which we will user to validate the user login detail. Now here is the code to make the httpost method.


        [HttpPost]

        public IActionResult LoginIndex(LoginModel loginModel)

        {

            string message;

            int responsetypeid;

            TestDBContext testDBContext = new TestDBContext();

            var loginstatus = testDBContext.UserLoginMasters.Where(m => m.LoginId == loginModel.LoginId && m.Password == loginModel.Password).FirstOrDefault();

            if (loginstatus != null)

            {

                message = "successful login";

                responsetypeid = 1;

            }

            else

            {

                message = "Invalid login detail";

                responsetypeid = 0;

            }

            return Json(new { message = message, status = responsetypeid });

        }



In above code I have is user detail provided I current then user will have the valid message other wise invalid detail and status code. In this we will make decision on the bases of status and display the message.

Now we will create the method to perform ajax validation in our asp.net core 6 login form.

<script src="~/lib/jquery/dist/jquery.js"></script>

<script>

    var UserLoginValudation = function () {

        //To capture the form data

        var formData = new FormData();

        var formcontroldata = $("#formlogin").serializeArray();

        $.each(formcontroldata, function (i, field) {

            formData.append(field.name, field.value);

        });

        $("#btnLogin").val("Please wait..");

        //To make the ajax request

        $.ajax({

            url: $("#formlogin").attr('action'),

            type: $("#formlogin").attr('method'),

            data: formData,

            contentType: false, // Not to set any content header

            processData: false, // Not to process data

            dataType: 'json',

            cache: false,

            success: function (result) {

                if (result.status == 0) {

                    $('#divmessage').prop('style', 'color:red');

                } else {

                    $('#divmessage').prop('style', 'color: green');

                }

                $("#btnLogin").val("Login");

                $("#divmessage").html(result.message);

            }

        });

    };

</script>



Now please check the complete cod of the page.
 

@model LoginProject.Models.LoginModel

 

@{

    ViewBag.Title = "Ajax Login form";

}

 

@using (Html.BeginForm("LoginIndex", "Home", FormMethod.Post, new { @Id = "formlogin" }))

{

    <div style="font-weight:bold; font-size:16px; color:red;" id="divmessage"></div>

    <div>

        <h2>User Registration</h2>

        <div class="row">

            <div class="form-group col-6">

                <lable for="loginid">Login Id</lable>

                @Html.TextBoxFor(m => m.LoginId, new { @class = "form-control", @placeholder = "Enter login id" })

            </div>

        </div>

        <div class="row">

            <div class="form-group col-6">

                <lable for="loginid">Password</lable>

                @Html.PasswordFor(m => m.Password, new { @class = "form-control", @placeholder = "Enter password" })

            </div>

        </div>

        <div class="row">

            <div class="form-group col-12">

                <input type="button" value="Login" onclick="javascript: UserLoginValudation();" id="btnLogin" />

            </div>

        </div>

    </div>

}

<script src="~/lib/jquery/dist/jquery.js"></script>

<script>

    var UserLoginValudation = function () {

        //To capture the form data

        var formData = new FormData();

        var formcontroldata = $("#formlogin").serializeArray();

        $.each(formcontroldata, function (i, field) {

            formData.append(field.name, field.value);

        });

        $("#btnLogin").val("Please wait..");

        //To make the ajax request

        $.ajax({

            url: $("#formlogin").attr('action'),

            type: $("#formlogin").attr('method'),

            data: formData,

            contentType: false, // Not to set any content header

            processData: false, // Not to process data

            dataType: 'json',

            cache: false,

            success: function (result) {

                if (result.status == 0) {

                    $('#divmessage').prop('style', 'color:red');

                } else {

                    $('#divmessage').prop('style', 'color: green');

                }

                $("#btnLogin").val("Login");

                $("#divmessage").html(result.message);

            }

        });

    };

</script>


Now we have done run the project and check the output. Add the invalid login detail and click on login. You will see that there is no postback and it will show you invalid login detail message.

Ajax Login Form Using jQuery  In Asp.net Core 6 Using C# Validate From Ms Sql Server Database

Ajax Login Form Using jQuery  In Asp.net Core 6 Using C# Validate From Ms Sql Server Database



Now add a valid detail and click on login.

Ajax Login Form Using jQuery  In Asp.net Core 6 Using C# Validate From Ms Sql Server Database


 


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

0 comments:

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