Hòa Nguyễn Coder
Posted on April 18, 2020
Today, I'm shared everyone a simple Login & Register in ASP.NET MVC 5
Step 1: Open Visual Studio 2019, File->New->Project
Step 2: Select ASP.NET Web Application(.NEt Framework)
Step 3: Enter name "Project"
Step 4: Choose Empty->checkbox MVC->Create
Okay,after when install project successfuly, now we can install **(EntityFramework,Bootstrap), you opent Nuget Packager Manager->search install it
You can again see: ASP.NET MVC 5 Install Bootstrap
If you install (EntityFramework, Bootstrap) success, continue create database in Project
Click right App_data->add database (name="DatabaseMVC5")
Configuation models, create User.cs class in Models directory
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ProjectMVC5.Models
{
public class User
{
[Key, Column(Order = 1)]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int idUser { get; set; }
[Required]
[StringLength(50, MinimumLength = 3)]
public string FirstName { get; set; }
[Required]
[StringLength(50, MinimumLength = 3)]
public string LastName { get; set; }
[Required]
[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]
public string Email { get; set; }
[Required]
[RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,15}$")]
public string Password { get; set; }
[NotMapped]
[Required]
[System.ComponentModel.DataAnnotations.Compare("Password")]
public string ConfirmPassword { get; set; }
public string FullName()
{
return this.FirstName + " " + this.LastName;
}
}
}
You can seen Form Validation
Ok, configuation extends DBcontext class, create DB_Entities.cs file in Models directory
+ Models/DB_Entities.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace ProjectMVC5.Models
{
public class DB_Entities: DbContext
{
public DB_Entities() : base("DatabaseMVC5") { }
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Database.SetInitializer<demoEntities>(null);
modelBuilder.Entity<User>().ToTable("Users");
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
base.OnModelCreating(modelBuilder);
}
}
}
You need insert connectstring to SQL SERVER in Web.config.cs file
<connectionStrings>
<add name="DatabaseMVC5" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DatabaseMVC5;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\DatabaseMVC5.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>
Okey, now we can create HomeController.cs in Controllers directory,
- Controllers/HomeController.cs ```csharp
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ProjectMVC5.Models;
using System.Security.Cryptography;
namespace ProjectMVC5.Controllers
{
public class HomeController : Controller
{
private DB_Entities _db = new DB_Entities();
// GET: Home
public ActionResult Index()
{
if (Session["idUser"] != null)
{
return View();
}
else
{
return RedirectToAction("Login");
}
}
//GET: Register
public ActionResult Register()
{
return View();
}
//POST: Register
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(User _user)
{
if (ModelState.IsValid)
{
var check = _db.Users.FirstOrDefault(s => s.Email == _user.Email);
if (check == null)
{
_user.Password = GetMD5(_user.Password);
_db.Configuration.ValidateOnSaveEnabled = false;
_db.Users.Add(_user);
_db.SaveChanges();
return RedirectToAction("Index");
}
else
{
ViewBag.error = "Email already exists";
return View();
}
}
return View();
}
public ActionResult Login()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(string email,string password)
{
if (ModelState.IsValid)
{
var f_password = GetMD5(password);
var data =_db.Users.Where(s => s.Email.Equals(email) && s.Password.Equals(f_password)).ToList();
if (data.Count() > 0)
{
//add session
Session["FullName"] = data.FirstOrDefault().FirstName +" "+ data.FirstOrDefault().LastName;
Session["Email"] = data.FirstOrDefault().Email;
Session["idUser"] = data.FirstOrDefault().idUser;
return RedirectToAction("Index");
}
else
{
ViewBag.error = "Login failed";
return RedirectToAction("Login");
}
}
return View();
}
//Logout
public ActionResult Logout()
{
Session.Clear();//remove session
return RedirectToAction("Login");
}
//create a string MD5
public static string GetMD5(string str)
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] fromData = Encoding.UTF8.GetBytes(str);
byte[] targetData = md5.ComputeHash(fromData);
string byte2String = null;
for (int i = 0; i < targetData.Length; i++)
{
byte2String += targetData[i].ToString("x2");
}
return byte2String;
}
}
}
**Register():** use Submit form add User to database
**Login():** check infomation people in database
**GetMD5():** create md5 string password
Create **Register.cshtml** file in **Views/Home** directory
```csharp
@model ProjectMVC5.Models.User
@{
ViewBag.Title = "Register";
Layout = "~/Views/Shared/_LayoutPage1.cshtml";
}
<div class="row justify-content-md-center">
<div class="col-md-5">
@using (Html.BeginForm("Register", "Home", FormMethod.Post))
{
//@Html.ValidationSummary()
@Html.AntiForgeryToken()
<div class="card">
<div class="card-header">
<div class="card-title">Register</div>
</div>
<div class="card-body">
<div class="form-group">
@Html.LabelFor(m => m.FirstName)
@Html.TextBoxFor(m => m.FirstName, "", new { @class = "form-control", @placeholder = "First Name" })
@Html.ValidationMessageFor(m => m.FirstName, "", new { @class = "badge badge-danger" })
</div>
<div class="form-group">
@Html.LabelFor(m => m.LastName)
@Html.TextBoxFor(m => m.LastName, "", new { @class = "form-control", @placeholder = "Last Name" })
@Html.ValidationMessageFor(m => m.LastName, "", new { @class = "badge badge-danger" })
</div>
<div class="form-group">
@Html.LabelFor(m => m.Email)
@Html.TextBoxFor(m => m.Email, "", new { @class = "form-control", @placeholder = "Email" })
@Html.ValidationMessageFor(m => m.Email, "", new { @class = "badge badge-danger" })
@if (ViewBag.error != null)
{
<span class="badge badge-danger">@ViewBag.error</span>
}
</div>
<div class="form-group">
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password, new { @class = "form-control", @placeholder = "Password" })
@Html.ValidationMessageFor(m => m.Password, "", new { @class = "badge badge-danger" })
</div>
<div class="form-group">
@Html.LabelFor(m => m.ConfirmPassword)
@Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control", @placeholder = "Confim Password" })
@Html.ValidationMessageFor(m => m.ConfirmPassword, "", new { @class = "badge badge-danger" })
</div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-danger" value="Register"/>
</div>
</div>
</div>
}
</div>
</div>
- Login.cshtml in Views/Home ```csharp
@model ProjectMVC5.Models.User
@{
ViewBag.Title = "Login";
Layout = "~/Views/Shared/_LayoutPage1.cshtml";
}
Login
@using (Html.BeginForm("Login", "Home", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.LabelFor(m => m.Email)
@Html.TextBoxFor(m => m.Email, "", new { @class = "form-control", @placeholder = "Email" })
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password, new { @class = "form-control", @placeholder = "Password" })
}
+ Create **Index.cshtml** file in Views/Home/ directory
```csharp
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_LayoutPage1.cshtml";
}
<div class="row justify-content-md-start">
<div class="col-md-4">
<div class="card">
<div class="card-header">
Wellcome
</div>
<div class="card-body">
@if (Session["FullName"] != null)
{
<p>Name: @Session["FullName"].ToString()</p>
<p>Email: @Session["Email"].ToString()</p>
<a href="@Url.Action("Logout","Home")" class="btn btn-warning">Logout</a>
}
</div>
</div>
</div>
</div>
You can see: Login and Register in ASP.NET MVC 5
Posted on April 18, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.