In the last asp.net article, we have discussed how to create custom login and registration in asp net MVC 5  without entity framework.

In this asp.net post, we will learn how we create a complete custom simple login, logout, and registration form system using entity framework with jquery validation in MVC with authentication.

We will do login and registration functionality with the help of entity framework, we will proceed step by step to learn the complete system.This Article is best for who is beginning with asp.net MVC and like to learn the best way for user registration and login which is used in real projects.

We will try to create a basic login and registration page where user can log in and can do the registration.

 

MVC Pattern

Dynamic Web Site is a web site whose contents vary depending on the user input. There are always three parts to any web site, which is defined as 3-Tier Architecture. At present, this 3-Tire Architecture in Modern Software Development is more identified by the name of MVC Pattern.

MVC is a Software Designing Pattern, which is the Best Designing Pattern. Using this pattern, any type of software can be easily designed, developed, debug manage, maintain, update, upgrade, and extend.

This pattern basically consists of three parts, which define the three Tiers of 3-Tier Architecture ie Client Tire as View Part of MVC Pattern, Middle Tire as Controller Part of MVC Pattern, and Server Tier as Modal Part of MVC Pattern. In this way, the 3-Tier Architecture is identified by the Modal, View, and Controller Part of the MVC pattern.

So Let’s Start and create a table Users for storing user data

Sql Script:

CREATE TABLE [dbo].[Company_Users](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](max) NOT NULL,
    [Email] [nvarchar](max) NOT NULL,
    [Address] [nvarchar](max) NULL,
    [Encryptedpassword] [nvarchar](max) NULL,
 CONSTRAINT [PK_TblUsers] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

 

So let’s by creating an Mvc Application
Add an Empty MVC Project
Step 1-Right Click on Model Folder and add Entity Framework in Project
Step 2-Right-click on Controller folder in the Project and add a controller
in your project i.e HomeController.
Step 3-Right Click on Model in the Project and Model classes for login and registration

LoginViewModel Class

public class LoginViewModel
    {
        [Required]
        [EmailAddress]
        [Display(Name = "Email: ")]
        public string Email { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Password: ")]
        public string Password { get; set; }
    }

RegistrationViewModel Class


public class RegistrationViewModel
    {
        
        [Required]
        [Display(Name = "Name: ")]
        public string Name { get; set; }

        [Required]
        [EmailAddress]
        [StringLength(150)]
        [Display(Name = "Email: ")]
        public string Email { get; set; }

        [Required]
        [Display(Name = "Address: ")]
        public string Address { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [StringLength(150, MinimumLength = 6)]
        [Display(Name = "Password: ")]
        public string Password { get; set; }
    }

 

Step 4-Create ActionResult for login and registration in HomeController

using MvcDemoProject.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace MvcDemoProject.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
        // GET: UserDetail
        //Login Authentication
        //Only able access this Actionmethod when User Log in
        [Authorize]
        public ActionResult UserDetail()
        {
            return View();
        }
        // GET:Login 
        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }
        //Post:Login 
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginViewModel LoginViewModel)
        {
            if (IsAuthenitcatedUser(LoginViewModel.Email, LoginViewModel.Password))
            {
                //MVC and Login Authentication
                FormsAuthentication.SetAuthCookie(LoginViewModel.Email, false);
                return RedirectToAction("UserDetail", "Home");
            }
            else
            {
                ModelState.AddModelError("", "Your credentail is incorrect");
            }
            return View(LoginViewModel);
        }
        // GET:Register return view
        [HttpGet]
        public ActionResult UserRegistration()
        {
            return View();
        }
        // Post:Register 
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult UserRegistration(RegistrationViewModel RegistrationViewModel)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    if (!IsEmailExist(RegistrationViewModel.Email))
                    {
                        using (DemoDataBaseEntities db = new DemoDataBaseEntities())
                        {
                            Company_Users userobj = new Company_Users
                            {
                                Email = RegistrationViewModel.Email,
                                Name = RegistrationViewModel.Name,
                                //for encryption you should use a strong and secure Algorithm
                                // I'm simply using Base64 for explanation purpose
                                Encryptedpassword = Base64Encode(RegistrationViewModel.Password),
                                Address = RegistrationViewModel.Address
                            };
                            db.Company_Users.Add(userobj);
                            if (db.SaveChanges()>0)
                            {
                                //Set MVC and Login Authentication
                                FormsAuthentication.SetAuthCookie(RegistrationViewModel.Email, false);
                                return RedirectToAction("UserDetail", "Home");
                            }
                            else
                            {
                                ModelState.AddModelError("", "Something went wrong please try again later!");
                            }
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "email already exist please try with diffrent one!");
                    }

                }
                else
                {
                    ModelState.AddModelError("", "Model is Invalid");
                }
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", e.Message);
            }
            return View();
        }
        public ActionResult SignOut()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }

        private bool IsEmailExist(string email)
        {
            bool IsEmailExist = false;
            using (DemoDataBaseEntities db = new DemoDataBaseEntities())
            {
                int count = db.Company_Users.Where(a => a.Email == email).Count();
                if (count > 0)
                {
                    IsEmailExist = true;
                }
            }
            return IsEmailExist;
        }
        private bool IsAuthenitcatedUser(string email, string password)
        {
            var encryptpassowrd = Base64Encode(password);
            bool IsValid = false;
            using (DemoDataBaseEntities db = new DemoDataBaseEntities())
            {
                int count = db.Company_Users.Where(a => a.Email == email && a.Encryptedpassword == encryptpassowrd).Count();
                if (count > 0)
                {
                    IsValid = true;
                }
            }
            return IsValid;
        }
        private static string Base64Encode(string PlainPassword)
        {
            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(PlainPassword);
            return System.Convert.ToBase64String(plainTextBytes);
        }

    }
}

 

Step 5-Create a View for each ActionResult , right-click on each ActionMethod and follow the below step in the image.

Index.cshtml

@{
    ViewBag.Title = "Index";
}

<h2>Welcome to Login and Registration Portal</h2>

UserDetail.cshtml

@{
    ViewBag.Title = "UserDetail";
}

<h2>Login User Detail</h2>
<h3>Hello User @HttpContext.Current.User.Identity.Name </h3>

Login.cshtml

@model MvcDemoProject.Models.LoginViewModel
@{
    ViewBag.Title = "Login";
}

<h2>Login</h2>
<div class="row">
    <div class="col-md-8">
        <section id="loginForm">
            @using (Html.BeginForm("Login", "Home", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
            {
                @Html.AntiForgeryToken()
                <h4>Use a local account to log in.</h4>
                <hr />
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                <div class="form-group">
                    @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
                    <div class="col-md-10">
                        @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
                        @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="form-group">
                    @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
                    <div class="col-md-10">
                        @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
                        @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <button class="btn btn-info" type="submit">Log in</button>
                    </div>
                </div>
                <p>
                    @Html.ActionLink("Click for Registration", "Register")
                </p>
            }
        </section>
    </div>
</div>

UserRegistration.cshtml

@model MvcDemoProject.Models.RegistrationViewModel
@{
    ViewBag.Title = "Register";
}
<h2>User Registration</h2>
@using (Html.BeginForm("UserRegistration", "Home", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
    <h4>Create a new account.</h4>
    <hr />
    @Html.ValidationSummary("", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Name, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Address, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Address, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <button class="btn btn-info" type="submit">Register</button>
        </div>
    </div>
}
Step 7-Final and Last Step we need to set the Authentication mode as Forms in the web.config file, Copy paste the below code in your <system.web> tag in web.config file.
<system.web>
       <authentication mode="Forms">
       <forms loginUrl="/Home/Login" timeout="20"></forms>
       </authentication>
</system.web>

DownLoad Source Code

Advantages of MVC / Why is MVC used?

  • With the help of MVC, you can get both the view part and the logic part i.e. designer and developer to work on a project simultaneously.
  • With this, you can group the related action/method of logic together and group the view and its specific model together. So that you can complete your project in a short time.
  • The code becomes easier to manage.
  • From one model you can attach with multiple view parts. In the MVC based prokect, you get ease in doing code modification.

MVC History

It was first introduced by Trygve Reenskaug at around 1970 in PARC. During that time it was introduced in a programming language called Smalltalk because at that time it was an object-oriented, dynamically typed reflective programming language. Later in 1980, Jim Althoff and his colleagues started implementing it with a new version of Smalltalk, and it was reported in The Journal of Object Technology (JOT) article around 1988.
Later, many architectural patterns such as hierarchical model – view – controller (HMVC), model – view – adapter (MVA), model – view – presenter (MVP), model – view – ViewModel (MVVM) introduce inspired by MVC.
On March 28, 1996, the WebObjects framework (which is a Java web application server and a server-based web application framework) (first written in Objective-C) was created by NeXT Software, Inc. After the use of this web framework started, the trend of MVC started.

The post Create Login,Signout and Registration in Asp .Net Mvc Using Entity appeared first on Software Development | Programming Tutorials.



Read More Articles