Friday 22 July 2016

How to create Registration and Login Module with Razor View Engine in Asp.Net MVC using binary format image file

How to create Registration and Login Module with Razor View Engine in Asp.Net MVC 4.0 using Upload Image without Image Handler

Note – Here we will create a Login Registration WelCome module using Razor View Engine with Ado.Net Entity Model. Then we will explain Registration form with file upload, where we will use how to save binary format data in SQL server and also retrieve it. After that we will also discuss the Login and Welcome page. Further we will also teach how to fetch the image saved in the database with binary format.

-- sql query---------

CREATE TABLE Emp_Info
(
Name varchar(50),
Gender varchar(50),
EmailId varchar(50) primary key ,
Password varchar(50),
MobileNo varchar(50),
UserImage varbinary (max)
)

--******************************----

1. First we take MVC based Application named LoginRegistration and   using  Ado.Net Entity Data Model like  this


Then we will add class which name is Employee for View Model respective data mentioned below

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace LoginRegistration.Models
{
public class Employee
{

[Required(ErrorMessage = "Please enter Name")]
[RegularExpression(@"^[a-zA-Z\s]+$", ErrorMessage = "Name should be proper format Like-:Kush")]
public string Name { get; set; }

[Required(ErrorMessage = "Please enter Gender")]
[StringLength(6, MinimumLength = 4, ErrorMessage = "your enter Male or FeMale have 6 string length")]
public string Gender { get; set; }

[Required(ErrorMessage = "Please enter EmailId")]
[EmailAddress(ErrorMessage = "Please enter valid EmailId")]
public string EmailId { get; set; }

[Required(ErrorMessage = "Please enter Password")]
public string Password { get; set; }

[Required(ErrorMessage = "Please enter Confirm Password")]
[Compare("Password", ErrorMessage = "Password and Confirm Password is not match")]
public string ConfirmPassword { get; set; }

[Required(ErrorMessage = "Please enter MobileNo")]
[RegularExpression(@"^[789]\d{9}$", ErrorMessage = "Please enter Mobile No Like -9555484663")]
public string MobileNo { get; set; }

[Required(ErrorMessage = "Please uploade image")]
[FileExtensions(Extensions = ".jpg,.png", ErrorMessage = "Please upload only jpg and  png  file")]
public HttpPostedFileBase UserImage { get; set; }
}
}

 We will create HomeController with ActionView RegistrationPage and  add strongly type View with Employee View Model. For more details kindly follow below mentioned snapshot



################### Registration Page ###################

Code for RegistrationPage.cshtml…………………………..

@model LoginRegistration.Models.Employee

@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>RegistrationPage</title>
</head>
<body>
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<link href="~/Content/Site.css" rel="stylesheet" />

@using (Html.BeginForm("RegistrationPage", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)

<fieldset>
<legend>Employee</legend>

<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>

<div class="editor-label">
@Html.LabelFor(model => model.Gender)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Gender)
@Html.ValidationMessageFor(model => model.Gender)
</div>

<div class="editor-label">
@Html.LabelFor(model => model.EmailId)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.EmailId)
@Html.ValidationMessageFor(model => model.EmailId)
</div>

<div class="editor-label">
@Html.LabelFor(model => model.Password)
</div>
<div class="editor-field">
@Html.PasswordFor(model => model.Password)
@Html.ValidationMessageFor(model => model.Password)
</div>

<div class="editor-label">
@Html.LabelFor(model => model.ConfirmPassword)
</div>
<div class="editor-field">
@Html.PasswordFor(model => model.ConfirmPassword)
@Html.ValidationMessageFor(model => model.ConfirmPassword)
</div>

<div class="editor-label">
@Html.LabelFor(model => model.MobileNo)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.MobileNo)
@Html.ValidationMessageFor(model => model.MobileNo)
</div>

<div class="editor-label">
@Html.LabelFor(model => model.UserImage)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.UserImage ,new { type="file" })
@Html.ValidationMessageFor(model => model.UserImage)
@Html.ValidationMessage("CustomError")
</div>


<p>
@ViewBag.msg
<input type="submit" value="Register" />
</p>
</fieldset>
}

<div>
@Html.ActionLink("Login Page ?", "LoginPage")
</div>
</body>
</html>

####################### end code ###################


#######################  Start Code ###################
Code for LoginPage.cshtml…………………………..

@model LoginRegistration.Models.Employee

@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>LoginPage</title>
</head>
<body>
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<link href="~/Content/Site.css" rel="stylesheet" />
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)


<table >

<tr>
<td>EmailId</td>
<td>@Html.TextBox("EmailId")
@Html.ValidationMessageFor(model => model.EmailId)</td>

</tr>
<tr>
<td>Password</td>
<td>@Html.Password("Password")
@Html.ValidationMessageFor(model => model.Password)</td>

</tr>
<tr><td><input type="submit" value="Login" id="btnlogin" />

@Html.ActionLink("New User","RegistrationPage")</td></tr>
<tr><td style="color:red">@ViewBag.msg</td></tr>

</table>
}

</body>
</html>

####################### end Code ###################

####################### WelCome  ###################
@model LoginRegistration.Models.Emp_Info
@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>WelCome</title>
<style type="text/css">
b
{
color:#0094ff;
font-family:Verdana;
margin-left:15px;
}
</style>
</head>
<body>
<div>
@if(Model !=null)
{
<table >
<tr><td><b>Name</b></td><td>@Model.Name</td></tr>
<tr><td><b>Gender</b></td><td>@Model.Gender</td></tr>
<tr><td><b>EmailId</b></td><td>@Model.EmailId</td></tr>
<tr><td><b>Mobile No</b></td><td>@Model.MobileNo</td></tr>
<tr><td><b>Photo</b></td><td>
<img src="data:image/png;base64,@Convert.ToBase64String(Model.UserImage,0,Model.UserImage.Length)"  style="margin-top:5px;margin-left:5px;width:101px;height:93px" /></td></tr>

</table>

}

</div>
</body>
</html>

####################### end code ###################


#######################  Show All Employee ###################

@model List<LoginRegistration.Models.Emp_Info>

@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>ShowAllEmp</title>
</head>
<body>

<table border="1" width="50%">
<tr><th>Name</th><th>Gender</th><th>EmailId</th><th>MobileNo</th><th>User Image</th></tr>

@for (int i = 0; i < Model.Count(); i++)
{

<tr><td>@Model[i].Name</td><td>@Model[i].Gender</td><td>@Model[i].EmailId</td><td>@Model[i].MobileNo</td>
<td>
<img src="data:image/png;base64,@Convert.ToBase64String(Model[i].UserImage,0,Model[i].UserImage.Length)" width="auto" height="75px" style="margin-top:5px;margin-left:5px" /></td></tr>
}
</table>
</body>
</html>
###################### End Code ###################

############Code for HomeController.cs #################
using LoginRegistration.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LoginRegistration.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/

public ActionResult Index()
{
return View();
}

// database object........
testEntities1 database = new testEntities1();


// Registration Page....

public ActionResult RegistrationPage()
{
return View();
}

[HttpPost]
public ActionResult RegistrationPage(Employee emp)
{


//if (!(emp.UserImage.ContentType == "image/jpeg" || emp.UserImage.ContentType == "image/gif"))
//{
//    ModelState.AddModelError("UserImage", "Please upload jpg and gif file only");


//}
if (emp.UserImage.ContentLength > (20 * 1024))
{

ModelState.AddModelError("UserImage", " ");
ModelState.AddModelError("CustomError", "File must  be less  20 kb ");
}
else
{

byte[] data = new byte[emp.UserImage.ContentLength];
emp.UserImage.InputStream.Read(data, 0, emp.UserImage.ContentLength);



Emp_Info employee = new Emp_Info
{
Name = emp.Name,
Gender = emp.Gender,
EmailId = emp.EmailId,
Password = emp.Password,
MobileNo = emp.MobileNo,
UserImage = data
};
database.Emp_Info.Add(employee);
database.SaveChanges();

ViewBag.msg = "Data saved Suceessfully";
}

return View();
}


// Login Page............

public ActionResult LoginPage()
{
return View();
}

[HttpPost]
public ActionResult LoginPage(FormCollection fc)
{
string emailid = fc["EmailId"].ToString();
string pass = fc["Password"].ToString();
//Emp_Info emp = (from u in database.Emp_Info where u.EmailId.Equals(emailid) select u).FirstOrDefault();
Emp_Info emp = database.Emp_Info.Where(m => m.EmailId == emailid).FirstOrDefault();

if (emp == null)
{
ViewBag.msg = "User is invalid";
}
else if (!emp.Password.Equals(pass))
{
ViewBag.msg = "Invalid Password please try again";
}
else
{
return View("WelComePage", emp);
}
return View();
}

// WelCome Page

public ActionResult WelComePage()
{
return View();
}

// Show All Employee

public ActionResult ShowAllEmp()
{
return View(database.Emp_Info.ToList());
}

}
}

Note: Please must change priority of Page in your MVC Application if you want to set Default page to LoginPage .In Visual Studio 10, 12, 13 there are need to change but now if you are working with latest IDE Visual Studio 2015 there are no need to it
Step
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace LoginRegistration
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "LoginPage", id = UrlParameter.Optional }
);
}
}
}

Result: 








1 comments: