In this article, we will learn, How to create custom login registration in ASP.NET MVC 5. If you are a newcomer and Just started learning the concept of ASP.NET MVC then you have come to the right place.I have specially written this article for newcomers developer and anyone wants to create custom login & registration form in asp.net MVC with database connection without using entity framework.
I read many articles in google and I notice that almost all article is based on using entity framework so that in this article I decided to write a post on how to create custom login registration in asp net MVC 5 without entity framework.
Today in this article I will explain the following points:
- How to create Login and Registration page in MVC with database
- Registration and Login form in MVC with jquery validation
So Let’s Start,First, we have to create a table for the stored user info, like name, email, password to the database.
SQL Script:
CREATE TABLE [dbo].[TblUsers](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](max) NULL,
[Email] [nvarchar](max) NOT NULL,
[Password] [nvarchar](max) NULL,
[ContactNo] [nvarchar](max) NULL,
CONSTRAINT [PK_TblUsers] PRIMARY KEY CLUSTERED
(
[Id] ASC
)
)
Key points in this article:
- Create a Empty MVC application.
- Create controller.
- Create Model.
- Create View depending on the controller.
- Create ActionResult for the actions.
What is MVC?
In simple language, if I say, this is a way in which we divide our database, logic, and visual Part. The full form of MVC is Model-View-Controller, which means that we have a known database as a model, and the logic part is known as the controller and the visual part is known as a view.
Talking about technical language, it is an architectural pattern with the help that we dividing a project into 3 components so that we can increase the security and productivity of the project. MVC is not about any special programming language because you can use it in any project whether it is in PHP, in ASP.NET, in Nodejs, in Python, you can use this architectural pattern method in everyone.
How does MVC work?
We have created an MVC diagram with the help of which one can easily know how MVC works. This diagram is different from another sample diagram but we will tell you the complete information about it.
User
Here the user can be any person who sends a specific URL or request to our project and wants a corresponding response or result of its specific URL or request.
Front controller
We can call this the main request and response system that takes a request from the user and sends its corresponding response back to the user.
Controller
When the process of request from the Front Controller is verified, then a specific controller is called which collects the data from the Model and the visual part from the view and sends the response back to the front controller.
View
In this, all the things are available that we have to send as a response to the user on a specific request.
Model
This is our data layer where we send the complete data of a database table or a specific data controller to a specific request and attach it to the view part.
Step 1-Open Visual Studio and create an Empty MVC Project
Step 2-Right-click on Controller folder and add two controllers in project i.e AccountController and HomeController.
Step 3-Right Click on Model for and add two classes i.e LoginViewModel and RegistrationViewModel and copy-paste the below code.
LoginViewModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace MvcDemoProject.Models
{
public class LoginViewModel
{
[Required]
[EmailAddress]
[StringLength(150)]
[Display(Name = "Email Address: ")]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[StringLength(150, MinimumLength = 6)]
[Display(Name = "Password: ")]
public string Password { get; set; }
}
}
RegistrationViewModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace MvcDemoProject.Models
{
public class RegistrationViewModel
{
public int Id { get; set; }
[Required]
[Display(Name = "Name: ")]
public string Name { get; set; }
[Required]
[EmailAddress]
[StringLength(150)]
[Display(Name = "Email Address: ")]
public string Email { get; set; }
[Required(ErrorMessage = "You must provide a phone number,Phone Number at least 10 digit")]
[Display(Name = "ContactNo")]
[DataType(DataType.PhoneNumber)]
[RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Not a valid phone number")]
public string ContactNo { get; set; }
[Required]
[DataType(DataType.Password)]
[StringLength(150, MinimumLength = 6)]
[Display(Name = "Password: ")]
public string Password { get; set; }
}
}
Step 4-Now Let’s create an action method in both controllers , I have created one action method in HomeController and six Action Method in AccountController.
Copy the Below code in HomeController
HomeController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcDemoProject.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
}
}
When we will run the MVC project then by default this action will be called and return the Index View.
AccountController
using MvcDemoProject.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace MvcDemoProject.Controllers
{
public class AccountController : Controller
{
SqlConnection con = new SqlConnection("Data Source=ASHOK\\SQLEXPRESS0;Initial Catalog=DemoDataBase;User ID=ap;Password=ap@1234");
// GET: UserInfo
[Authorize]
public ActionResult UserInfo()
{
return View();
}
// GET:Login this Action method simple return the Login View
[HttpGet]
public ActionResult Login()
{
return View();
}
//Post:When user click on the submit button then this method will call
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginViewModel LoginViewModel)
{
if (IsValidUser(LoginViewModel.Email, LoginViewModel.Password))
{
FormsAuthentication.SetAuthCookie(LoginViewModel.Email, false);
return RedirectToAction("UserInfo", "Account");
}
else
{
ModelState.AddModelError("", "Your Email and password is incorrect");
}
return View(LoginViewModel);
}
// GET:Register return view
[HttpGet]
public ActionResult Register()
{
return View();
}
// Post:Register
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(RegistrationViewModel RegistrationViewModel)
{
try
{
if (ModelState.IsValid)
{
//checking if user already exist
if (!IsUserExist(RegistrationViewModel.Email))
{
string query = "insert into TblUsers values (@Name,@Email,@Password,@ContactNo)";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("@Name", RegistrationViewModel.Name);
cmd.Parameters.AddWithValue("@Email", RegistrationViewModel.Email);
// encode password i'm using simple base64 you can use any more secure algo
cmd.Parameters.AddWithValue("@Password", Base64Encode(RegistrationViewModel.Password));
cmd.Parameters.AddWithValue("@ContactNo", RegistrationViewModel.ContactNo);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
if (i > 0)
{
FormsAuthentication.SetAuthCookie(RegistrationViewModel.Email, false);
return RedirectToAction("UserInfo", "Account");
}
else
{
ModelState.AddModelError("", "something went wrong try later!");
}
}
}
else
{
ModelState.AddModelError("", "User with same email already exist!");
}
}
else
{
ModelState.AddModelError("", "Data is not correct");
}
}
catch (Exception e)
{
ModelState.AddModelError("", e.Message);
}
return View();
}
public ActionResult LogOut()
{
FormsAuthentication.SignOut();
return RedirectToAction("Index", "Home"); }
private bool IsUserExist(string email)
{
bool IsUserExist = false;
string query = "select * from TblUsers where Email=@email";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("@email", email);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
if (dt.Rows.Count > 0)
{
IsUserExist = true;
}
}
return IsUserExist;
}
private bool IsValidUser(string email, string password)
{
var encryptpassowrd = Base64Encode(password);
bool IsValid = false;
string query = "select * from TblUsers where Email=@email and Password=@Password";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("@Email", email);
cmd.Parameters.AddWithValue("@Password", encryptpassowrd);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
if (dt.Rows.Count > 0)
{
IsValid = true;
}
}
return IsValid;
}
public static string Base64Encode(string plainText)
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
public static string Base64Decode(string base64EncodedData)
{
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}
}
}
Step 5-Now Let’s create a View for each action method, right-click on each ActionMethod and click on add View with Use Layout Check selected.
If you checkmark “Use Layout” option then it automatically creates Master _Layout.cshtml View in the “Shared” folder and also create bootstrap files in your project.
After adding View for each ActionMethod your View folder should look like at the below image.
Step 6-Now Copy Paste the Below Code in Login and Registration View
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", "Account", 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">
<input type="submit" value="Log in" class="btn btn-default" />
</div>
</div>
<p>
@Html.ActionLink("Register as a new user", "Register")
</p>
}
</section>
</div>
</div>
Register.cshtml
@model MvcDemoProject.Models.RegistrationViewModel
@{
ViewBag.Title = "Register";
}
<h2>Register</h2>
@using (Html.BeginForm("Register", "Account", 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.ContactNo, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.ContactNo, 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">
<input type="submit" class="btn btn-default" value="Register" />
</div>
</div>
}
UserInfo.cshtml
@{
ViewBag.Title = "UserInfo";
}
<h2>UserInfo</h2>
<h3>Hello User @HttpContext.Current.User.Identity.Name </h3>
_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="~/Scripts/modernizr-2.6.2.js"></script>
<style>
.field-validation-error{
color:red;
}
</style>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@if (Request.IsAuthenticated)
{
<strong>@Html.Encode(User.Identity.Name)</strong>
<a href="@Url.Action("","")" class = "navbar-brand">Logout</a>
}
else
{
<a href="@Url.Action("","")" class = "navbar-brand">Register</a>
<span> | </span>
<a href="@Url.Action("","")" class="navbar-brand">Login</a>
}
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
</ul>
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
</body>
</html>
Last and Final Step :
<authentication mode="Forms">
<forms defaultUrl="/Home/Index" loginUrl="/Home/Index" slidingExpiration="true" timeout="2880"></forms>
</authentication>
The post Login And Registration in Asp .Net MVC Without Entity Framework 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#
- Login form and Registration form without using database
- Track Log In Attempts Without Using Database - ASP Net C#
- Log out and redirect user to login screen ASP NET MVC / C #
- How to pass DataTable or any collection to cshtml view in asp mvc without Entity Framework
- how to sort data from database in listview using c# and entity framework
- How can we compact a access database in VB.NET or C#.NET without using DAO and JRO
- Without using database how Can I Search for a word and display it's related content in another field
- Entity Framework Database Connection in Single-Threaded Application
- Store file in SQL Server database using .Net MVC3 with Entity Framework
- asp.net using loginview and login status without membership
- Using Controllers without the entire MVC Framework
- How do I redirect the user to a view once they've logged in and attempted to go back to the login screen ASP NET CORE
- How to run two functions simultaneously without pausing each other in asp net mvc
- Change a database table name using Entity Framework code first migrations
- WinForms Entity Framework database connection exception at design-time
- MVC Application hanging when using Tasks.WhenAll with Entity Framework SaveChangesAsync
- Azure Mobile Service - Entity Framework Code First drop and create database not working
- Entity Framework with Linked Database and SQL Views
- How to create two DropDownList from differents model in the same view using ASP MVC SQL and EF
- How to show the current user using ASP MVC and EF
- How to determine the next primary key from a database table for a generic entity using Entity Framework Core?
- How to create new database by new client with Net core 3 and Entity Framework?
- How to pass SQL query parameters without single apostrophes using Entity Framework Core?
- Get foreign key records using Entity Framework and display in Angular
- How to construct an instance of a view-model when using Asp.Net MVC 5 framework and IoC container?
- Hide Print button and nav menu in PDF using Rotativa PDF generator in Asp MVC 5
- Entity Framework code-first and existing database
- How to create nlog loggers for various controllers and asp net mvc filters?
- How to create nlog loggers for various controllers and asp net mvc filters?
- C# reading large excel xlsx and writing data to sql server express database with entity framework performance issues
- What rules and conventions should a class follow to be able to work properly with NHibernate?
- Replacing XML innerText with XMLElement or XElement
- WPF Panel where only one item is visible at a time (alternative to QML's StackLayout)?
- How can i check if a vector2 (touch input) is inside every rectTransform of a rectTransform[] array?
- How would you convert this to valid VB.NET?
- Convert int to little-endian formated bytes in C++ for blobId in Azure
- How to change my MVC Website's Current Culture at Runtime
- Read data from a Gif
- Is it possible to use T4MVC and Asynchronous operations?
- MVC Model binding not working as expected on complex type from AJAX request
- JavaScript with c# doesn't work
- Is there a function to save the number of checked checkboxes in a variable?
- Possible way to reduce translation properties with MVVM in WPF
- How to make a regex pattern that fits
- C# MySQL as multiline string
- DataGrid AutoGeneratingColumn Action in Caliburn.Micro
- WCF Service Application VS ASP.NET Web Application?
- GetConstructors vs. _baseType.GetMethod("GetConstructorImpl", BindingFlags.NonPublic | BindingFlags.Instance)
- How to store Expression<Func<T, object>> in a class field?
- Repeater - bind a button to a field