Asp.Net Core MVC Ajax Enable Login Page Using jQuery, C#.Net

How to create an ajax enabled login page or form (without page refresh) using asp.net core mvc using Entity framework, jQuery and c#.net.
In today's article I will show a simple tutorial with example how you can create an asp.net core mvc ajax enabled login form using jQuery and C#.net, Validate user credential without page refresh in asp.net core mvc. With the help of Scaffold DBContext we will be able to connect to database with entity framework with our .net core mvc application.  So, for this article first we will create SQL table and add some records. 

Login table in SQL

After creating SQL table, we will create a new asp.net core 8 mvc application with c#.net and add a model class file and add the below given class code property. 

public class UserLoginModel
{
    public string LoginId { get; set; }
    public string Password { get; set; }
} 
After creating model class, we will create DB context to make connection to MS SQL server using Entity framework. Please check syntax to connect to database. 
Scaffold command syntax Scaffold-DbContext "Server=<MS SQL Server Name>;Database=<Database name>;Trusted_Connection=True;TrustServerCertificate=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir data
Now we will create a HttpGet method in controller and add the below code in it. 
[HttpGet]
public IActionResult Index()
{
    UserLoginModel userLoginModel = new UserLoginModel();
    return View(userLoginModel);
} 
Here in above code, I have passed the object of model class to view. Now let's create the view.
@model UserLoginModel
@{
    ViewData["Title"] = "Index";
}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
    <div style="color:red;font-weight:bold;display:none;" id="divMessage">Invalid login detail...</div>
    <div class="page-wrapper box-content">
        <label>Login Id:</label>
        @Html.TextBoxFor(m => m.LoginId, new { @class = "form-control", @id = "txtLoginId" })<br />
        <label>Password:</label>
        @Html.PasswordFor(m => m.Password, new { @class = "form-control", @id = "txtPassword" })<br />
    </div>
    <input type="button" value="Login" onclick="javascript: Login();" id="btnLogin"/>
}
<script>
    var Login=function(){
        $("#btnLogin").val("Please wait...");
      $.ajax({
        url: "/Home/Index/",
        type: 'POST',
        data : {LoginId : $("#txtLoginId").val(),Password: $("#txtPassword").val()},
        success: function(response){
            if(response==0){
                 $("#btnLogin").val("Login");
                 $("#divMessage").show();
            }else{
                window.location.href="/Home/Success/";
            }
          alert(response);
         },
        error: function(error){
          console.log(error)
        }
    });
    }
</script> 
In above code I have added model class reference. After adding model class reference, I have added jQuery library reference. In next line I have added form reference, and I have added TextBoxfor and PasswordFor control to ask user to enter user id and password. 
Now here I have used jQuery Ajax function. Here I have passed the login id bad password. Here if we get 0 on that case user will get invalid message and if we are getting 1 on that case we will redirect to user to success page. I have used .show() to make div controller visible at client side. Now lets check user id validation code.
[HttpPost]
public int Index(UserLogin userLogin)
{
    EmployeeContext employeeContext = new EmployeeContext();
    var status = employeeContext.EmpLogins.Where(m => m.LoginId == userLogin.LoginId && 
    m.Password == userLogin.Password).FirstOrDefault();
    if (status != null)
    {
        return 1;
    }
    else
    {
        return 0;
    }
} 
Here in above code, I have created object of DB context and validated user id and password from Database.  In validation credential scenario will return 1 otherwise will return 0.  At the end create success page to redirect user to the page on successful login.
public IActionResult Success()
{
    return View();
} 
Now we have done let's run code and check the output. Here we will add a wrong credential as shown below.

Login form

Now press Login button.  We will get please wait on login button as shown below.

Login form with please wait

Now let's check the code break point.  

Invalid Login Detail

Now let's add correct login detail and check the output. 

Correct Login Detail

Here we have added correct login detail we will get redirected to success page.

Success Page

Post a Comment