Thumb

How To Create Login Page In ASP.NET MVC | Using Jquery Ajax | Login & Registration Demo | Part-3

10/13/2019 12:00:00 AM

Step-1

In this part i will show how to create and login page in ASP.NET MVC using  Jquery Ajax. First open visual studio and open our existing project where we are working. In this Register Controller first create a method name as CheckValidUser. This method receive  a parameter name as SiteUser. Into this method string result is false when DataItem  will be not null then result true  and assign session  and return json result. Afterlogin method are responsible to if session is not null then this method return view otherwise redirect  to register controller index method. In this controller Logout method responsible to session are null and redirect to  register controller in index view. Given bellow the controller code:

using LoginRegistrationDemo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;

namespace LoginRegistrationDemo.Controllers
{
    public class RegisterController : Controller
    {
        MVCTutorialEntities db = new MVCTutorialEntities();
        public ActionResult Index()
        {
            return View();
        }

        public JsonResult SaveData(SiteUser model)
        {
            model.IsValid = false;
            db.SiteUsers.Add(model);
            db.SaveChanges();
            BuildEmailTemplate(model.ID);
            return Json("Registration Successfull", JsonRequestBehavior.AllowGet);
        }
        public ActionResult Confirm(int regId)
        {
            ViewBag.regID = regId;
            return View();
        }
        public JsonResult RegisterConfirm(int regId)
        {
            SiteUser Data = db.SiteUsers.Where(x => x.ID == regId).FirstOrDefault();
            Data.IsValid = true;
            db.SaveChanges();
            var msg = "Your Email Is Verified!";
            return Json(msg, JsonRequestBehavior.AllowGet);
        }
        public void BuildEmailTemplate(int regID)
        {
            string body = System.IO.File.ReadAllText(HostingEnvironment.MapPath("~/EmailTemplate/") + "Text" + ".cshtml");
            var regInfo = db.SiteUsers.Where(x => x.ID == regID).FirstOrDefault();
            var url = "http://localhost:58464/" + "Register/Confirm?regId=" + regID;
            body = body.Replace("@ViewBag.ConfirmationLink", url);
            body = body.ToString();
            BuildEmailTemplate("Your Account Is Successfully Created", body, regInfo.Email);
        }

        public static void BuildEmailTemplate(string subjectText, string bodyText, string sendTo)
        {
            string from, to, bcc, cc, subject, body;
            from = "YourEmail@gmail.com";
            to = sendTo.Trim();
            bcc = "";
            cc = "";
            subject = subjectText;
            StringBuilder sb = new StringBuilder();
            sb.Append(bodyText);
            body = sb.ToString();
            MailMessage mail = new MailMessage();
            mail.From = new MailAddress(from);
            mail.To.Add(new MailAddress(to));
            if (!string.IsNullOrEmpty(bcc))
            {
                mail.Bcc.Add(new MailAddress(bcc));
            }
            if (!string.IsNullOrEmpty(cc))
            {
                mail.CC.Add(new MailAddress(cc));
            }
            mail.Subject = subject;
            mail.Body = body;
            mail.IsBodyHtml = true;
            SendEmail(mail);
        }

        public static void SendEmail(MailMessage mail)
        {
            SmtpClient client = new SmtpClient();
            client.Host = "smtp.gmail.com";
            client.Port = 587;
            client.EnableSsl = true;
            client.UseDefaultCredentials = false;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.Credentials = new System.Net.NetworkCredential("YourEmail@gmail.com", "Password");
            try
            {
                client.Send(mail);
            }
            catch(Exception ex){
                throw ex;
            }
        }

        public JsonResult CheckValidUser(SiteUser model)
        {
            string result = "Fail";
            var DataItem = db.SiteUsers.Where(x => x.Email == model.Email && x.Password == model.Password).SingleOrDefault();
            if (DataItem != null)
            {
                Session["UserID"] = DataItem.ID.ToString();
                Session["UserName"] = DataItem.Username.ToString();
                result = "Success";
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public ActionResult AfterLogin()
        {
            if (Session["UserID"] != null)
            {
                return View();
            }
            else
            {
                return RedirectToAction("Index");
            }
        }

        public ActionResult Logout()
        {
            Session.Clear();
            Session.Abandon();
            return RedirectToAction("Index");
        }
	}
}

Step-2

 In log In view first write some javascript code. This javascript get the value from html tag by the id using  jQuery. Also by the jQuery some html tag hide and show. Now when javascript get the value from the html then Ajax call to post the value into server site. If value are successfully submit then controller return the success massage and when the controller return false then the view are not change. This form submit use the onclick method. Given bellow the view code:

@{
    ViewBag.Title = "Index";
    Layout = null;
}



<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />

<div class="container" style="margin-top:10%">
    <div class="row">
        <div class="col-md-4 col-md-offset-4 alert alert-info">
            <h3 class="text-center">Login</h3>
            <form id="loginForm">
                <div id="msg"><ul style="color:red;"> Invalid Username Or Password</ul></div>
                <div class="form-group">
                    <div class="input-group">
                        <span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
                        <input class="form-control" type="email" name="Email" id="logEmail" placeholder="Email" />
                    </div>
                </div>

                <div class="form-group">
                    <div class="input-group">
                        <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
                        <input class="form-control" type="password" name="Password" id="logPssword" placeholder="Password" />
                    </div>
                </div>
            </form>
            <div class="form-group">
                <button class="btn btn-info form-control" type="submit" onclick="Login()"><i class="glyphicon glyphicon-log-in"></i> Login</button> 
            </div>
            <div class="form-group">
                <a style="float:left">Forget Password ? </a><a style="float:right;cursor:pointer" onclick="SignUp()"> Sign Up</a>
            </div>
        </div>
    </div>
</div>

@*Design Modal With Registration form*@

<div class="modal fade" id="ShowModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <a href="#" class="close" data-dismiss="modal">&times;</a>
                <h4>Registration Form</h4>
                <div id="message1">
                    <div class="alert alert-success">
                        <span class="glyphicon glyphicon-ok"></span><strong>Success Message!<br />
                        send an email to your email address with confirmation link!<br />
                        please check your inbox
                        </strong>
                    </div>
                </div>
                <div id="message2">
                    <div class="alert alert-danger">
                        <span class="glyphicon glyphicon-remove"></span><strong>Error Message! Your Registration Is Not Complete</strong>
                    </div>
                </div>
            </div>
            <div class="modal-body">
                <form id="Registration">
                    <div class="form-group">
                        <div class="input-group">
                            <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
                            <input class="form-control" type="text" name="Username" id="user" placeholder="Username" />
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="input-group">
                            <span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
                            <input class="form-control" type="email" name="Email" id="Email" placeholder="Email" />
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="input-group">
                            <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
                            <input class="form-control" type="password" name="Password" id="Password" placeholder="Password" />
                        </div>
                    </div>
                </form>
                <div class="form-group">
                    <button class="btn btn-info form-control" type="submit" onclick="SaveForm()"><i class="glyphicon glyphicon-registration-mark"></i> Submit</button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    function SignUp() {
        $("#ShowModal").modal();
        $("#message1").hide();
        $("#message2").hide();
    }

    function SaveForm() {
        var name = $("#user").val();
        var pwd = $("#Password").val();
        var email = $("#Email").val();

        if (name == "" || pwd == "" || email == "") {
            $("#message1").hide();
            $("#message2").show();
            return false;
        }
        var data = $("#Registration").serialize();
        $.ajax({
            type: "post",
            data: data,
            url: "/Register/SaveData",
            success: function (result) {
                
                $("#message1").show();
                $("#message2").hide();
                $("#Registration")[0].reset();
            }
        });
    }

    //Login System
    $("#msg").hide();

    var Login = function () {
        var data = $("#loginForm").serialize();
        $.ajax({
            type: "post",
            url: "/Register/CheckValidUser",
            data: data,
            success: function (result) {
                if (result == "Fail") {
                    $("#loginForm")[0].reset();
                    $("#msg").show();
                }
                else {
                    window.location.href = "/Register/AfterLogin";
                    $("#msg").hide();
                }
            }
        })
    }
</script>

 

Step-3

 Now build and Run the project.

About Teacher

Image

Reza Karim

Software Engineer

More about him