In this article I will show how to create a Login and Registration form in ASP.Net MVC. This is a quick simple example of how to implement it in ASP.NET MVC project.
Before implementing the steps given below create a table in your database as I have created for this project:
create table mvcUser
(
FirstName varchar(50),
LastName varchar(50),
userID varchar(50) constraint mvcPrime primary key,
PasswordConfirm varchar(30),
StreetAddress1 varchar(100),
StreetAddress2 varchar(100),
City varchar(50),
State varchar(50),
ZIPCode varchar(20)
)
Please implement the following steps to create a Login and Registration Form:
· Open Microsoft Visual Studio 2010 à Select New Project à Select Web from the Installed Templates à Select ASP.NET MVC 3 Web Application à Enter the project name “UserFormDemo” in the Name textbox à Click OK.
After select the project you can see the following (New ASP.NET MVC 3 Project) dialog box:
Select Empty from the Select a template option à Select ASPX view engine à Click OK.
Add a new Controller in your project and enter the controller name as “HomeController” as shown in the below figure:
After adding a controller add a Model in your project and enter the model class name as “Login.cs”.
You also have to configure your web.config and Globax.asax file for the implementation of this project:
Add connectionStrings element under configuration tag and authentication element under system.web tag.
<connectionStrings>
<add name="cs"connectionString="Data source=server_name; Initial Catalog=database_name; User Id=user_id; Password=user_password" providerName="System.Data.SqlClient" />
</connectionStrings>
<authentication mode="Forms">
<forms loginUrl="~/Home/LogOn"defaultUrl="~/Home/Home"timeout="2880" />
</authentication>
Change the RegisterRoutes definition in Global.asax file as show below:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "LogOn", id = UrlParameter.Optional }
);
}
In the Model class add the properties, methods and class as I did in the below Model (Login) class:
using System;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Web.Mvc;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;
namespace UserFormDemo.Models
{
public class Login
{
[Required(ErrorMessage = "Email Id Required")]
[DisplayName("Email ID")]
[RegularExpression(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$",
ErrorMessage = "Email Format is wrong")]
[StringLength(50, ErrorMessage = "Less than 50 characters")]
public string EmailId
{
get; set;
}
[DataType(DataType.Password)]
[Required(ErrorMessage="Password Required")]
[DisplayName("Password")]
[StringLength(30, ErrorMessage = ":Less than 30 characters")]
public string Password
{
get; set;
}
public bool IsUserExist(string emailid, string password)
{
bool flag = false;
SqlConnection connection = new SqlConnection(
System.Configuration.ConfigurationManager.ConnectionStrings["cs"].ConnectionString);
connection.Open();
SqlCommand command = new SqlCommand("select count(*) from mvcUser where
userID='" + emailid + "' and PasswordConfirm='" + password + "'", connection);
flag = Convert.ToBoolean(command.ExecuteScalar());
connection.Close();
return flag;
}
}
public class Register
{
[Required(ErrorMessage="FirstName Required:")]
[DisplayName("First Name:")]
[RegularExpression(@"^[a-zA-Z'.\s]{1,40}$",ErrorMessage="Special Characters not
allowed")]
[StringLength(50, ErrorMessage = "Less than 50 characters")]
public string FirstName { get; set; }
[Required(ErrorMessage="LastName Required:")]
[RegularExpression(@"^[a-zA-Z'.\s]{1,40}$", ErrorMessage = "Special Characters
not allowed")]
[DisplayName("Last Name:")]
[StringLength(50, ErrorMessage = "Less than 50 characters")]
public string LastName { get; set; }
[Required(ErrorMessage="EmailId Required:")]
[DisplayName("Email Id:")]
[RegularExpression(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$",
ErrorMessage = "Email Format is wrong")]
[StringLength(50, ErrorMessage = "Less than 50 characters")]
public string EmailId { get; set; }
[Required(ErrorMessage="Password Required:")]
[DataType(DataType.Password)]
[DisplayName("Password:")]
[StringLength(30, ErrorMessage = "Less than 30 characters")]
public string Password { get; set; }
[Required(ErrorMessage="Confirm Password Required:")]
[DataType(DataType.Password)]
[Compare("Password", ErrorMessage = "Confirm not matched.")]
[Display(Name = "Confirm password:")]
[StringLength(30, ErrorMessage = "Less than 30 characters")]
public string ConfirmPassword { get; set; }
[Required(ErrorMessage="Street Address Required")]
[DisplayName("Street Address1:")]
[StringLength(100, ErrorMessage = "Less than 100 characters")]
public string StreetAdd1 { get; set; }
[DisplayName("Street Address2:")]
[StringLength(100, ErrorMessage = "Less than 100 characters")]
public string StreetAdd2 { get; set; }
[Required(ErrorMessage="City Required")]
[DisplayName("City:")]
[RegularExpression(@"^[a-zA-Z'.\s]{1,40}$", ErrorMessage = "Special Characters
not allowed")]
[StringLength(50, ErrorMessage = "Less than 50 characters")]
public string City { get; set; }
[Required(ErrorMessage="State Required")]
[DisplayName("State:")]
[RegularExpression(@"^[a-zA-Z'.\s]{1,40}$", ErrorMessage = "Special Characters
not allowed")]
[StringLength(50, ErrorMessage = "Less than 50 characters")]
public string State { get; set; }
[Required(ErrorMessage="ZipCode Required")]
[DisplayName("Zip Code:")]
[StringLength(20, ErrorMessage = "Less than 20 characters")]
public string Zip { get; set; }
[Required(ErrorMessage = "Enter Verification Code")]
[DisplayName("Verification Code:")]
public string Captcha { get; set; }
public bool IsUserExist(string emailid)
{
bool flag = false;
SqlConnection connection = new SqlConnection
(System.Configuration.ConfigurationManager.ConnectionStrings["cs"].ConnectionString);
connection.Open();
SqlCommand command = new SqlCommand("select count(*) from mvcUser where
userID='" + emailid + "'", connection);
flag = Convert.ToBoolean(command.ExecuteScalar());
connection.Close();
return flag;
}
public bool Insert()
{
bool flag = false;
if (!IsUserExist(EmailId))
{
SqlConnection connection = new SqlConnection
(System.Configuration.ConfigurationManager.ConnectionStrings["cs"].ConnectionString);
connection.Open();
SqlCommand command = new SqlCommand("insert into mvcUser values('" +
FirstName + "','" + LastName + "','" + EmailId + "','" + Password + "',
'" + StreetAdd1 + "','" + StreetAdd2 + "','" + City + "','" + State +"',
'" + Zip + "')", connection);
flag = Convert.ToBoolean(command.ExecuteNonQuery());
connection.Close();
return flag;
}
return flag;
}
}
public class CaptchImageAction : ActionResult
{
public Color BackgroundColor { get; set; }
public Color RandomTextColor { get; set; }
public string RandomText { get; set; }
public override void ExecuteResult(ControllerContext context)
{
RenderCaptchaImage(context);
}
private void RenderCaptchaImage(ControllerContext context)
{
Bitmap objBmp = new Bitmap(150, 60);
Graphics objGraphic=Graphics.FromImage(objBmp);
objGraphic.Clear(BackgroundColor);
SolidBrush objBrush = new SolidBrush(RandomTextColor);
Font objFont = null;
int a;
string myFont, str;
string[] crypticsFont = new string[11];
crypticsFont[0] = "Times New roman";
crypticsFont[1] = "Verdana";
crypticsFont[2] = "Sylfaen";
crypticsFont[3] = "Microsoft Sans Serif";
crypticsFont[4] = "Algerian";
crypticsFont[5] = "Agency FB";
crypticsFont[6] = "Andalus";
crypticsFont[7] = "Cambria";
crypticsFont[8] = "Calibri";
crypticsFont[9] = "Courier";
crypticsFont[10] = "Tahoma";
for (a = 0; a < RandomText.Length; a++)
{
myFont = crypticsFont[a];
objFont=new Font(myFont,18,FontStyle.Bold | FontStyle.Italic |
FontStyle.Strikeout);
str=RandomText.Substring(a,1);
objGraphic.DrawString(str,objFont,objBrush,a*20,20);
objGraphic.Flush();
}
context.HttpContext.Response.ContentType="image/GF";
objBmp.Save(context.HttpContext.Response.OutputStream,ImageFormat.Gif);
objFont.Dispose();
objGraphic.Dispose();
objBmp.Dispose();
}
}
}
Add the following Views and methods in the Controller class:
using System;
using System.Web.Mvc;
using System.Web.Security;
using System.Drawing;
using System.Text;
using UserFormDemo.Models;
namespace MvcApplication.Controllers
{
public class HomeController : Controller
{
public ViewResult LogOn()
{
return View();
}
public ViewResult Register()
{
return View();
}
public ActionResult Home()
{
return View();
}
[HttpPost, ValidateInput(false)]
public ActionResult LogOn(Login model)
{
if (ModelState.IsValid)
{
if (model.IsUserExist(model.EmailId, model.Password))
{
ViewBag.UserName = model.EmailId;
FormsAuthentication.RedirectFromLoginPage(model.EmailId, false);
}
else
{
ModelState.AddModelError("", "EmailId or Password Incorrect.");
}
}
return View(model);
}
[HttpPost, ValidateInput(false)]
public ActionResult Register(Register model)
{
if (ModelState.IsValid)
{
string realCaptcha = Session["captcha"].ToString();
if (model.Captcha == realCaptcha)
{
if (model.Insert())
{
return RedirectToAction("LogOn", "Home");
}
else
{
ModelState.AddModelError("", "Email Id Already Exist");
}
}
else
ModelState.AddModelError("", "Verification Code is Incorrect");
}
return View(model);
}
public CaptchImageAction Image()
{
string randomText = SelectRandomWord(6);
Session["captcha"] = randomText;
HttpContext.Session["RandomText"] = randomText;
return new CaptchImageAction() { BackgroundColor = Color.LightGray,
RandomTextColor = Color.Black, RandomText = randomText };
}
private string SelectRandomWord(int numberOfChars)
{
if (numberOfChars > 36)
{
throw new InvalidOperationException("Random Word Characters cannot be
greater than 36");
}
char[] columns = new char[36];
for (int charPos = 65; charPos < 65 + 26; charPos++)
columns[charPos - 65] = (char)charPos;
for (int intPos = 48; intPos <= 57; intPos++)
columns[26 + (intPos - 48)] = (char)intPos;
StringBuilder randomBuilder = new StringBuilder();
Random randomSeed = new Random();
for (int incr = 0; incr < numberOfChars; incr++)
{
randomBuilder.Append(columns[randomSeed.Next(36)].ToString());
}
return randomBuilder.ToString();
}
}
}
After establishing the code you have to add the Master Page and Views in your project to present the user interface:
· Adding a Master Page:
Right click on Shared Folder à Add New Item à Select MVC 3 view Master Page (ASPX) à Enter the Site.Master in the Name textbox à Click Add.
Add the following content in the Master Page (Site.Master):
<html>
<head id="Head1" runat="server">
<script type="text/javascript">
function Cancel() {
location.href = "Logon";
}
</script>
<style type="text/css">
h1
{
color:Blue;
margin:10px 0px 0px 40%;
font-family:Calibri;
}
a
{
color:Black;
text-decoration:none;
font-size:large;
font-family:Calibri;
}
table
{
margin-top:0px;
}
</style>
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
</head>
<body style="background-color:Aqua">
<script src="<%: Url.Content("~/Scripts/jquery-1.4.4.min.js") %>"
type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/JavaScript/jquery-ui-1.8.7.min.js")%>"
type="text/javascript"></script>
<script src="<%: Url.Content("~/Scripts/jquery.validate.min.js") %>"
type="text/javascript"></script>
<script src="<%: Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js") %>"
type="text/javascript"></script>
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
<div>
<h1>Welcome to My Site</h1>
<hr />
<table align="right">
<tr>
<td>
<%: Html.ActionLink("[Register]","Register") %>
<%: Html.ActionLink("[Log On]","LogOn") %>
</td>
</tr>
</table>
<asp:ContentPlaceHolder ID="MainContent" runat="server" />
</div>
</body>
</html>
Add a view:
· Enter View name as LogOn.
· Select Login class as a strongly typed view.
· Select Site.master as your master page.
Add the following content in your LogOn View source page:
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
LogOn
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<style type="text/css">
.btnStyle
{
border: thin solid #000000;
line-height: normal;
width: 80px;
}
</style>
<%using (Html.BeginForm("LogOn", "Home", FormMethod.Post))
{ %>
<div class="fontStyle">
<center>
<table style="margin-top: 100px;margin-left:150px">
<tr>
<td colspan="2">
<div>
<asp:Image ID="Image1" runat="server"
ImageUrl="~/Content/Multi_purpose.png" Width="250px" />
<hr />
</div>
</td>
</tr>
<tr style="height:30px">
<td align="right">
<%: Html.LabelFor(m => m.EmailId) %>
</td>
<td style="width:200px" align="right">
<%: Html.TextBoxFor(m => m.EmailId)%>
</td>
<td style="width:250px;color:Red" align="left">
<%: Html.ValidationMessageFor(m => m.EmailId)%>
</td>
</tr>
<tr style="height:30px">
<td align="right">
<%:Html.LabelFor(m => m.Password) %>
</td>
<td align="right">
<%: Html.PasswordFor(m => m.Password)%>
</td>
<td style="width:250px;color:Red" align="left">
<%: Html.ValidationMessageFor(m => m.Password) %>
</td>
</tr>
<tr style="height:30px">
<td colspan="2" align="center">
<input type="submit" value="Sign In" class="btnStyle" />
</td>
</tr>
<tr>
<td colspan="3" style="color:Red;" align="left">
<%: Html.ValidationSummary(true)%>
</td>
</tr>
</table>
</center>
</div>
<%} %>
</asp:Content>
Add a view:
· Enter View name as Register.
· Select Register class as a strongly typed view.
· Select Site.master as your master page.
Add the following content in your Register View source page:
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Register
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<style type="text/css">
.btnStyle
{
border: thin solid #000000;
line-height: normal;
width: 80px;
}
</style>
<%using (Html.BeginForm("Register", "Home", FormMethod.Post))
{ %>
<div>
<table style="margin-left: 350px" align="center">
<tr>
<td>
<table style="font-family: Calibri">
<tr style="height: 80px">
<td colspan="2" align="center">
<asp:Label ID="lblBanner" runat="server" Text="Register
New Account" Font-Names="Consolas" Font-Size="Larger" Font-
Underline="True"></asp:Label>
</td>
</tr>
<tr>
<td style="width: 200px">
<%: Html.LabelFor(m => m.FirstName) %>
</td>
<td style="width: 150px">
<%: Html.TextBoxFor(m => m.FirstName) %>
</td>
<td style="width: 200px; color: Red" align="left">
<%: Html.ValidationMessageFor(m => m.FirstName) %>
</td>
</tr>
<tr>
<td>
<%: Html.LabelFor(m => m.LastName) %>
</td>
<td>
<%: Html.TextBoxFor(m => m.LastName) %>
</td>
<td style="color: Red">
<%: Html.ValidationMessageFor(m => m.LastName) %>
</td>
</tr>
<tr>
<td>
<%: Html.LabelFor(m => m.EmailId) %>
</td>
<td>
<%: Html.TextBoxFor(m => m.EmailId) %>
</td>
<td style="color: Red">
<%: Html.ValidationMessageFor(m => m.EmailId) %>
</td>
</tr>
<tr>
<td>
<%: Html.LabelFor(m => m.Password) %>
</td>
<td>
<%: Html.PasswordFor(m => m.Password) %>
</td>
<td style="color: Red">
<%: Html.ValidationMessageFor(m => m.Password) %>
</td>
</tr>
<tr>
<td>
<%: Html.LabelFor(m => m.ConfirmPassword) %>
</td>
<td>
<%: Html.PasswordFor(m => m.ConfirmPassword) %>
</td>
<td style="color: Red">
<%: Html.ValidationMessageFor(m => m.ConfirmPassword) %>
</td>
</tr>
<tr>
<td>
<%: Html.LabelFor(m => m.StreetAdd1) %>
</td>
<td>
<%: Html.TextBoxFor(m => m.StreetAdd1) %>
</td>
<td style="color: Red">
<%: Html.ValidationMessageFor(m => m.StreetAdd1) %>
</td>
</tr>
<tr>
<td>
<%: Html.LabelFor(m => m.StreetAdd2) %>
</td>
<td>
<%: Html.TextBoxFor(m => m.StreetAdd2) %>
</td>
<td style="color: Red">
<%: Html.ValidationMessageFor(m => m.StreetAdd2) %>
</td>
</tr>
<tr>
<td>
<%: Html.LabelFor(m => m.City) %>
</td>
<td>
<%: Html.TextBoxFor(m => m.City) %>
</td>
<td style="color: Red">
<%: Html.ValidationMessageFor(m => m.City) %>
</td>
</tr>
<tr>
<td>
<%: Html.LabelFor(m => m.State) %>
</td>
<td>
<%: Html.TextBoxFor(m => m.State) %>
</td>
<td style="color: Red">
<%: Html.ValidationMessageFor(m => m.State) %>
</td>
</tr>
<tr>
<td>
<%: Html.LabelFor(m => m.Zip) %>
</td>
<td>
<%: Html.TextBoxFor(m => m.Zip) %>
</td>
<td style="color: Red">
<%: Html.ValidationMessageFor(m => m.Zip) %>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="image" id="image" src="<%:
Url.Action("Image","Home") %>" alt="Click to Refresh" />
</td>
</tr>
<tr>
<td>
<%: Html.LabelFor(m => m.Captcha) %>
</td>
<td>
<%: Html.TextBoxFor(m => m.Captcha) %>
</td>
<td style="color: Red">
<%: Html.ValidationMessageFor(m => m.Captcha) %>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Register" class="btnStyle" />
<input type="button" value="Cancel" onclick="return
Cancel()" class="btnStyle" />
</td>
</tr>
<tr>
<td colspan="2" style="color: Red" align="right">
<%: Html.ValidationSummary(true) %>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
<%} %>
</asp:Content>
Add a view:
· Enter View name as Home.
· Select Login class as a strongly typed view.
Add the following content in your Home View source page:
<html>
<head runat="server">
<title>Home</title>
</head>
<body>
<div>
<h2>Welcome User!</h2>
</div>
</body>
</html>
Now both coding and design part is over. Now when you debug or run your project you will have the following screen from which user can login if he had registered in the database.
When you click on the Register link, a registration page will open from where user can registered:
After creating or registering account when user login he will get the following page with welcome message:
Source From : www.mindstick.com/Articles