Register & Login form in Photo Gallary




  • The Register and Login functionality is important in user based applications.
  • We have used jQuery majorly to make the Register and Login form very interesting.


Screenshot :


  • This is the main page. We have used an image which covers most of the page.
  • We have register and Login link on the right top. 
  • On clicking the links the form opens up. We have used jQuery for this.

Controller :

public ActionResult LoginRegister()
        {
            Main registerViewModel = new Main();
            return View(registerViewModel);
        }

This is the Action method which renders the main page. 
We are creating an object of Main class which is our ViewModel to the view.

ViewModel :




using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using PhotoGallary.Models;
using PhotoGallary.CustomValidator;

namespace PhotoGallary.ViewModels
{
    public class Main
    {
        public Register Register { get; set; }
        public Login Login { get; set; }
    }

    public class Register
    {
        [Required(ErrorMessage = "Required")]
        public string FirstName { get; set; }

        [Required(ErrorMessage = "Required")]
        public string LastName { get; set; }

        [Required(ErrorMessage = "Required")]
        public string Username { get; set; }

        [Required(ErrorMessage = "Required")]
        public string Password { get; set; }

    }

    public class Login
    {
        public string LoginUserName { get; set; }

        public string LoginPassword { get; set; }
    }
}


  • The above is our ViewModel. We are actually passing two view models as a part of one class.
  • In the Main class we have created properties of Register and Login class.
  • In the Register class we have used DataAnnotation attributes to validate the user's input.

View :

@model PhotoGallary.ViewModels.Main

@{
    ViewBag.Title = "LoginRegister";
}

<h1 align="center">Photo Gallary</h1>
<input type="hidden" id="IsValid" name="IsValid" value="@ViewBag.isValid"/>
<img style="position:absolute" src='@Url.Content("~/Content/Images/MainPageGallary.PNG")' alt="MainImage"/>
<span id="RegisterSpan" style="position:absolute;right:20px;cursor:pointer;">Register</span>
<span id="LoginSpan" style="position:absolute;right:20px;top:100px;cursor:pointer;">Login</span>
@using(Html.BeginForm("LoginRegister","LoginRegister"))
{
<div id="RegisterDiv" style="position:absolute;right:20px;width:400px;height:300px;background-color:#232323;color:white;font-family:comic sans ms;display:none;">
   <span id="Success" style="color:White;font-family: comic sans ms;margin-left:40px;"></span>
    <table style="width:100%;height: 100%;margin-left:20px;">
        <tr>
            <td style="width: 100px;">
                @Html.LabelFor(model => model.Register.FirstName)
            </td>
            <td style="width:150px;">
                @Html.TextBoxFor(model => model.Register.FirstName)
            </td>
            <td>
                @Html.ValidationMessageFor(model => model.Register.FirstName)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(model => model.Register.LastName)
            </td>
            <td>
                @Html.TextBoxFor(model => model.Register.LastName)
            </td>
    <td>
                @Html.ValidationMessageFor(model => model.Register.LastName)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(model => model.Register.Username)
            </td>
            <td>
                @Html.TextBoxFor(model => model.Register.Username)
            </td>
    <td>
                @Html.ValidationMessageFor(model => model.Register.Username)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(model => model.Register.Password)
            </td>
            <td>
                @Html.PasswordFor(model => model.Register.Password)
            </td>
    <td>
                @Html.ValidationMessageFor(model => model.Register.Password)
            </td>
        </tr>
        <tr>
            <td>
                <button id="RegisterButton" type="submit" style="cursor:pointer;">Register</button>
            </td>
            <td>
                <input type="button" style="cursor:pointer;" id="CancelButton" value="Cancel"/>
            </td>
        </tr>
    </table>
</div>
}

<div id="LoginDiv" style="position:absolute;right:20px;width:300px;height:200px;background-color:#232323;color:white;font-family:comic sans ms;display:none;">
    <span id="ValidationText" style="color:Red;font-family: comic sans ms;margin-left:40px;"></span>
 <table style="width:100%;height: 100%;margin-left:20px;">
        <tr>
            <td>
                @Html.LabelFor(model => model.Login.LoginUserName,"Username")
            </td>
            <td>
                @Html.TextBoxFor(model => model.Login.LoginUserName)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(model => model.Login.LoginPassword,"Password")
            </td>
            <td>
                @Html.PasswordFor(model => model.Login.LoginPassword)
            </td>
        </tr>
        <tr>
            <td>
                <button id="LoginButton" style="cursor:pointer;">Login</button>
            </td>
            <td>
                <button id="LoginCancelButton" style="cursor:pointer;">Cancel</button>
            </td>
        </tr>
    </table>
</div>
<script type="text/javascript">
    $("#RegisterSpan").click(function () {
        $("#RegisterDiv").show("slow");
    });

    $("#CancelButton").click(function () {
        $("#Success").html("");
        $("#RegisterDiv").hide("slow");
        $("input[type=text]").val("");
        $("input[type=password]").val("");
        location.href = '@Url.Action("LoginRegister","LoginRegister")';
    });

    $("#LoginSpan").click(function () {
        $("#LoginDiv").show("slow");
    });

    $("#LoginCancelButton").click(function () {
        $('#Login_LoginUserName').val("");
        $('#Login_LoginPassword').val("");
        $("#LoginDiv").hide("slow");
        location.href = '@Url.Action("LoginRegister","LoginRegister")';
    });


    $(document).ready(function () {
        var isValid = $("#IsValid").val();
        if (isValid == "False") {
            $("#RegisterDiv").show();
        } else if (isValid == "True") {
            $("#Success").html("Registration Successfully Done.");
            $("#Register_FirstName").val("");
            $("#Register_LastName").val("");
            $("#Register_Username").val("");
            $("#RegisterDiv").show();
        }
        $('#LoginButton').click(function () {
            var username = $("#Login_LoginUserName").val();
            var password = $("#Login_LoginPassword").val();
            if (username == "" && password == "") {
                $("#ValidationText").html("Enter Username and Password");
                return;
            }
            else if (username == "") {
                $("#ValidationText").html("Enter Username");
                return;
            }
            else if (password == "") {
                $("#ValidationText").html("Enter Password");
                return;
            }
            $.ajax({
                url: '@Url.Action("Login","LoginRegister")',
                type: 'POST',
                data: { userName: username, password: password },
                success: function (data) {
                    if (data.value == "Invalid") {
                        $("#ValidationText").html("Invalid USername and Password");
                    } else {
                        location.href = '@Url.Action("UserProfile","LoginRegister")';
                    }
                },
                error: function () {
                    alert("error");
                }
            });

        });
    });

</script>


  • The above is our view. As mentioned earlier, we have passed two view models to this view. 
  • One for Register form and other for Login. 
  • The Register form posts data to following controller method on submit.

Action Method post for Regiser form :

[HttpPost]
        public ActionResult LoginRegister(Main main)
        {
            if (ModelState.IsValid)
            {
                Gallary gallary = new Gallary();
                ViewBag.isValid = true;
                bool isSaved = gallary.SaveRegisterDetails(main.Register);
                return View(main);
            }
            else
            {
                ViewBag.isValid = false;
                return View(main);
            }
        }


  • The register form data is posted to the above action method. We are passing the object of Main class. 
  • The DataAnnotation validated the properties and if the form is valid then the user details are saved, otherwise the viewmodel object with error messages are returned back to the view.
  • As you can see in the above action method. We have a class named Gallary, which is our service class.
  • The SaveRegisterDetails in Gallary class is as below :
Service Method :

public bool SaveRegisterDetails(Register register)
        {
            using(GallaryDataContext dbContext = new GallaryDataContext())
            {
                LoginDetails details = new LoginDetails();
                details.FirstName = register.FirstName;
                details.LastName = register.FirstName;
                details.Username = register.Username;
                details.Password = register.Password;
                dbContext.LoginDetails.InsertOnSubmit(details);
                dbContext.SubmitChanges();
            }
            return true;
        }

The above method saves the user details into the database. We have created a separate service class to hold methods that queries with database and return results.

Action Method post for Login form :

[HttpPost]
        public ActionResult Login(string userName,string password)
        {
            Gallary gallary = new Gallary();
            bool isValid = gallary.ValidateCredentials(userName,password);
            if (isValid)
            {
                Session["Username"] = userName;
                Session["password"] = password;
                int userId = gallary.GetUserIdByUsernamePassword(userName, password);
                Session["UserId"] = userId;
                return Json(new { userName = userName, password = password });
            }
            else
            {
                return Json(new {value = "Invalid"});
            }
        }

  • We have not used form for posting Login details. On login click we are collecting the username and password and posting data to above action method using AJAX post.
  • If the user credentials are validated positively then user is redirected to first page, otherwise validation message is shown.
  • Below are the service methods used in the Action method.
Service Method :

public bool ValidateCredentials(string username,string password)
        {
            using(GallaryDataContext dbContext = new GallaryDataContext())
            {
                LoginDetails User = new LoginDetails();
                User = dbContext.LoginDetails.Where(detail => detail.Username == username && detail.Password == password).SingleOrDefault();
            }
            if (User == null)
                return false;
            else
            {
                return true;
            }
        }

        public int GetUserIdByUsernamePassword(string username, string password)
        {
            using(GallaryDataContext dbContext = new GallaryDataContext())
            {
                return dbContext.LoginDetails.Where(user => user.Username == username && user.Password == password).Single().RegisterId;
            }
        }
The ValidateCredentials method validated the user with database and returns true or false accordingly.
Thus we have seen the code used to create the Register and login functionality for Photo Gallary.

0 comments:

Post a Comment