We provide IT Services

Register Now Click On

Read More Tutorials Click On

Post Page Advertisement [Top]


In This Article, we provide How to create Login Page in asp.net MVC 5


Step 1: Create a Project:-



Select Visual C#, Web under Installed templates. After that select ASP.NET MVC 5 Web Application....


Project template selects a template as Basic, then view the engine as Razor. Click OK.


Create database connection select Data ADONET Entity Data Model


Select Generate from database and then click on Next.


Click on New Connection,

Clicking on New Connection,
  • Provide the Server name.
  • Select the "Use SQL Server Authentication" radio button.
  • Enter the User name and Password.
  • Select the "Select or enter a database name:" radio button.
  • Select the database you want to set the connection.
  • Check the "Save my password" checkbox.
  • Click on the "Test Connection".
  • Then click OK.

Select radio button: Yes include the sensitive data in the connection string.

Choose your database objects, as in the following image.


Step 3: Add a Controller

Go to Solution Explorer, Right-click on Controller folder, Add and then click on Controller.


Controller Code:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using schoolManagementSystem.Models;
using schoolManagementSystem.Repository;
namespace schoolManagementSystem.Controllers
{
    public class AccountsController : Controller
    {
        private SchoolManagementSystemdbcontext _db = new SchoolManagementSystemdbcontext();
        #region View
        public ActionResult Registration()
        {
            return View();
        }
        public ActionResult Login()
        {
            if (Session["UserName"] != null && Session["EmailId"] != null)
            {
                return RedirectToAction("Index", "Home");
            }
            return View();
        }

        public ActionResult Logout()
        {
            Session["UserName"] = null;
            Session["EmailId"] = null;
            return RedirectToAction("Login", "Accounts");
        }
        public ActionResult ForgotPassword()
        {
            return View();
        }
        public ActionResult Index()
        {
            return View();
        }

        #endregion View

        [HttpPost]
        public ActionResult Registrationclient(string FirstName, string LastName, string Email, string Password)
        {
            try
            {
                var IsExistUser = _db.Registrations.Any(x => x.EmailId == Email.Trim());
                if (!IsExistUser)
                {
                    Registration reg = new Registration();
                    Account IP = new Account();
                    string IpAddress = IP.GetIPAddress();
                    Session["Email"] = Email;
                    Session["UserName"] = FirstName;
                    reg.UserName = FirstName;
                    reg.LastName = LastName;
                    reg.EmailId = Email;
                    reg.Password = Password;
                    reg.IpAddress = IpAddress;
                    reg.Create_Date = reg.ClientId == 0 ? DateTime.Now : reg.Create_Date;
                    _db.Registrations.Add(reg);
                    _db.SaveChanges();
                    return Json("Registration Successfully !", JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json("User Already Exist", JsonRequestBehavior.AllowGet);
                }
                //return Json(new { result = Newtonsoft.Json.JsonConvert.SerializeObject(errmsg), Value = value }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                throw;
            }
        }

        [HttpPost]
        public ActionResult LoginData(string EmailId, string Password, string UserName, bool chkremember)
        {
            Session["UserName"] = UserName;
            Session["EmailId"] = EmailId;

            if (chkremember == true)
            {
                if (Request.Browser.Cookies)
                {
                    {
                        HttpCookie CookiesDetails = new HttpCookie("CookiesDetails");
                        CookiesDetails["UserName"] = UserName.ToString();
                        CookiesDetails["EmailId"] = EmailId.ToString();
                        CookiesDetails["Password"] = Password.ToString();
                        //CookiesDetails.Expires = DateTime.Now.AddDays(60);
                        Response.Cookies.Add(CookiesDetails);
                    }
                }
                else
                {
                    HttpCookie CookiesDetails = new HttpCookie("CookiesDetails");
                    CookiesDetails["chkremember"] = "False";
                }
            }

            Account logindata = new Account();
            dynamic Logindetail = logindata.Logindata(EmailId, Password);

            if (Logindetail == true)
            {
                return Json("Done", JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json("User Name and Password Incoorect", JsonRequestBehavior.AllowGet);
            }
        }

    }

}

Step 4: Create Views


View Code:-

@{
    Layout = "~/Views/Shared/_LogLayout.cshtml";
}
<script src="~/scripts/Accounts/Login.js"></script>

<div class="spinner-section" id="Spinner">
</div>

<div class="bgimg">
    <div class="container">
        <div class="card card-login mx-auto mt-5">
            <div class="card-header">Login</div>
            <div class="card-body">
                <form class="form" id="FrmAELogin" action="" method="post">
                    <div class="form-group">
                        <div class="form-row">
                            <div class="col-xs-12 col-sm-12 col-md-12">
                                <label for="inputEmail">UserName</label>
                                <input type="email" id="txtAEUserName" name="txtAEUserName" class="form-control form-control-sm checkSpcialChar" placeholder="User Name" required="required" autofocus="autofocus">
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="form-row">
                            <div class="col-xs-12 col-sm-12 col-md-12">
                                <label for="inputEmail">Email address</label>
                                <input type="email" id="txtAEEmailId" name="txtAEEmailId" class="form-control form-control-sm checkSpcialChar" placeholder="Email address" required="required" autofocus="autofocus">
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="form-row">
                            <div class="col-xs-12 col-sm-12 col-md-12">
                                <label for="inputPassword">Password</label>
                                <input type="password" id="txtAEPassword" name="txtAEPassword" class="form-control form-control-sm checkSpcialChar" placeholder="Password" required="required">
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="checkbox">
                            <label>
                                <input type="checkbox" id="chkbtn" value="remember-me">
                                Remember Password
                            </label>
                        </div>
                    </div>
                    <input type="button" value="Login" id="btnlogin" class="btn btn-primary btn-block" data-saveurl="@Url.Action("Logindata","Accounts")" />
                </form>
                <div class="text-center">
                    <a class="d-block small mt-3" href="~/Accounts/Registration">Register an Account</a>
                    <a class="d-block small" href="~/Accounts/ForgotPassword">Forgot Password?</a>
                </div>
            </div>
        </div>
    </div>
</div>

Step 5 Create DataModel Class:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using schoolManagementSystem.Models;
namespace schoolManagementSystem.Repository
{
    public class Account
    {
        private SchoolManagementSystemdbcontext _db = new SchoolManagementSystemdbcontext();
        public string GetIPAddress()
        {
            string IPAddress = "";
            IPHostEntry Host = default(IPHostEntry);
            string Hostname = null;
            Hostname = System.Environment.MachineName;
            Host = Dns.GetHostEntry(Hostname);
            foreach (IPAddress IP in Host.AddressList)
            {
                if (IP.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    IPAddress = Convert.ToString(IP);
                }
            }
            return IPAddress;
        }

        public dynamic Logindata(string EmailId, string Password)
        {
            dynamic orderHeaders;
            try
            {
                orderHeaders = _db.Registrations.Any(a => a.EmailId.Equals(EmailId) && a.Password.Equals(Password));
            }
            catch (Exception)
            {
                throw;
            }
            return orderHeaders;
        }
    }

}

Step 6 Create .js File.

$(document).ready(function () {
    $("#Spinner").hide();
    $("#btnlogin").on("click", function () {
        Logindata(); 
    });
});

function Logindata() {
    debugger
    var EmailId = $("#txtAEEmailId").val();
    var Password = $("#txtAEPassword").val();
    var UserName = $("#txtAEUserName").val();
   
    var chkremember = false
    if ($("#chkbtnRemember").is(':checked')) {
        chkremember = true;
    }
    $.ajax({
        url: $("#btnlogin").attr('data-saveurl'),
        type: 'Post',
        cache: false,
        data: { "EmailId": EmailId, "Password": Password, "UserName": UserName, "chkremember": chkremember },
        dataType: 'json',
        beforeSend: function () {
            $("#Spinner").show();
        },
        success: function (data) {
            $("#Spinner").show();
            if (data == 'Done') {
                location.href = "/Home/Index";
            }
            else if (data == 'User Name and Password Incoorect') {
                swal({
                    title: "Login",
                    text: "<p class='lead text-muted'>" + data + " </p>",
                    type: "error",
                    showCancelButton: false,
                    html: true,
                    confirmButtonClass: 'btn-success',
                    confirmButtonText: 'OK'
                });
            }
        },
        complete: function () {
            $("#Spinner").hide();
        },
        error: function () {
            $("#Spinner").hide();
            swal({
                title: "Login",
                text: "<p class='lead text-muted'>" + data + " </p>",
                type: "error",
                showCancelButton: false,
                html: true,
                confirmButtonClass: 'btn-error',
                confirmButtonText: 'OK'
            });
        },
    });
}

Step 7: Run the Application


Final DashBoard:-


No comments:

Post a comment

| Designed by Rockprogrammer