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]
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);
}
}
}
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>
}
<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
The post Create Login,Signout and Registration in Asp .Net Mvc Using Entity appeared first on Software Development | Programming Tutorials.
Read More Articles
- Write a value which contain comma to a CSV file in c#?
- Reading CSV File with cells containing commas c#
- Split CSV with columns may contain ‘,’ Comma C#
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- [Simple Way]-ASP.NET Core Upload Multiple File Web API model
- [Simple Way]- Image Upload in .NET Core Web API
- [Easy Way]-Receive File and other form data together in ASP.NET Core Web API
- Replace image in word document using C#
- How to add new rows to an existing word document table in C#
- How to sync model after using Code First from Database using Entity Framework 6.1 and MVC 5?
- how to create an audit trail with Entity framework 5 and MVC 4
- Is This How to Create a Data Transfer Object (DTO) with Entity Framework Core & ASP.NET Core MVC 2.2+ and 3.0
- Download and display a private Azure Blob using ASP MVC
- Cookie expiry in ASP NET Core Authentication using Azure AD OpenIdConnect and custom middleware
- Check if a folder exist in a directory and create them using C#
- How do you clear cookies using asp.net mvc 3 and c#?
- How do I create a C# array using Reflection and only type info?
- Can you create sql views / stored procedure using Entity Framework 4.1 Code first approach
- unobtrusive client validation using fluentvalidation and asp.net mvc LessThanOrEqualTo not firing
- Programmatically create a web site in IIS using C# and set port number
- How to create Select List for Country and States/province in MVC
- How do I resolve Web API controllers using Autofac in a mixed Web API and MVC application?
- Using XmlSerializer to create an element with attributes and a value but no sub-element
- WPF - How can I create menu and submenus using binding
- How to create a response message and add content string to it in ASP.NET 5 / MVC 6
- Create a hyperlink using Xamarin.Forms (xaml and c#)
- Debug both javascript and c# in ASP.NET Core MVC using VS Code
- ASP NET MVC 5 Delete File From Server
- Adding a controller with read/write actions and views, using Entity Framework - what is "Data Context class"?
- Trying to create a new .xlsx file using NPOI and write to it
- How to create and connect custom user buttons/controls with lines using windows forms
- How to create a nuget package with both release and debug dll's using nuget package explorer?
- Disable registration template in ASP NET core
- MVC and Entity Framework Html.DisplayNameFor with Composite ViewModel
- How to create a test run and result using the Team Foundation Server API?
- How to read / write geography data using C#, Entity Framework and SQL Server 2008?
- Authentication and Authorization without Entity Framework in ASP.NET 5 MVC 6
- How to get access token from httpcontext using owin and Mvc 5
- Add Keys and Values to RouteData when using MVCContrib to unit test MVC 3 controllers and Views
- How do I get the length of a window class name so I know how large of a buffer to allocate?
- Deserializing JSON with numbers as keys
- Constants in .NET with String.Format
- Library to write javascript code
- Visual Studio IIS HTTP 503 Service Unavailable
- Get value from ModelState with key name
- Posting Dynamic Forms in ASP.NET MVC 3
- How to add new operator in C# using Roslyn
- Can protractor test a login that is not angular based
- Mapping Table to Entity
- Uploading objects to google cloud storage buckets in c#
- How to pick a background color depending on font color to have proper contrast
- Java and C# interoperability
- Allocation free delegate or other way to call method by address?
- Use libphonenumber to validate mobile phone number without knowing the country
- Visual Studio won't find class in separate .cs file
- CA1500 vs. SA1309 - Which one wins?
- How to create video streaming using C#
- Add query string as route value dictionary to ActionLink
- The type 'IEnumerable<>' is defined in an assembly that is not referenced