Tuesday 2 June 2015

How to implements Validation(View Model) in Mvc using AutoMapper

AutoMapper is used to reduce the complexity we find when binding the model and communicating with entities. It is an open source library provided by GitHub. The Codeplex page says about AutoMapper: “AutoMapper is an object-object mapper. Object-object mapping works by transforming an input object of one type into an output object of a different type. You can get the AutoMapper from the following website: AutoMapper.

--Sql  Server  query
create  database  test
use  test

create  table Employee
(
EmpId int primary key,
Name varchar(50),
Age int,
EmailId varchar(50),
Password varchar(50),
Address varchar(50),
PinCode varchar(50),
UserImage varchar(50),
CreditCard varchar(50),
WebSitesUrl varchar(50)
)
Note: we are arranging this class for validation concept in our application then we will add ViewModel Folder in Models and add class which name is  EmployeeInfo ,  code  of EmployeeInfo class  is  given below.

using System;
using System.Collections.Generic;
//using this name  space.............
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace MvcApplication2.Models
{
public class EmployeeInfo
{
//[Required]
[Required(ErrorMessage = "Please enter EmpId")]
public int EmpId { get; set; }

[Required(ErrorMessage = "Please enter Name")]
[StringLength(6, ErrorMessage = "Name length b/w 1 to 6")]
public string Name { get; set; }

[Required(ErrorMessage = "Please enter Age")]
[Range(1, 70, ErrorMessage = "Age b/w 1 to 75")]
public int Age { 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 Address")]
public string Address { get; set; }

[Required(ErrorMessage = "Please enter Pin Code")]
[RegularExpression(@"\d{6}")]
public string PinCode { get; set; }

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

[Required(ErrorMessage = "Please enter Credit Card No")]
[CreditCard(ErrorMessage = "Please enter valid CreditCard No")]
public string CreditCard { get; set; }

[Required(ErrorMessage = "Please enter Website url")]
[Url(ErrorMessage = "Please enter valid url")]
public string WebSitesUrl { get; set; }
}
}
Then next step we add AutoMapper dll in our Application how to add dll
Right click in our Application 
Manage NewGut Packages
Select  online
Next  steps in form of pictures are given below.



add entity Model in our Mvc Application from database test  after  that  we will Object-object mapping works by transforming an input object (EmployeeInfo (ViewModel) of one type into an output object of a different type (Employee (DataBase entities)) by  using AutoMapper



Next step we will add Controller  which  name is  HomeController  and  the  code  of  controller  is  given below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AutoMapper;
using MvcApplication2.Models;
using System.IO;

namespace MvcApplication2.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
testEntities1 tt = new testEntities1();
public ActionResult Index()
{
return View();


}

[HttpPost]
public ActionResult Index(EmployeeInfo ep, HttpPostedFileBase UserImage)
{
//var allowedExtensions = new[] { ".jpg", ".jpge" };
//var extension = Path.GetExtension(f1.FileName);

if (UserImage.ContentLength <= 10885)
{
//if (allowedExtensions.Contains(extension))
//{

var filename = Path.GetFileName(UserImage.FileName);
var path = Path.Combine(Server.MapPath("~/UserImages/"), filename);
UserImage.SaveAs(path);

Mapper.CreateMap<MvcApplication2.Models.EmployeeInfo, MvcApplication2.Models.Employee>();

var emp = Mapper.Map<MvcApplication2.Models.EmployeeInfo, MvcApplication2.Models.Employee>(ep);

emp.UserImage = UserImage.FileName;
tt.Employees.Add(emp);
tt.SaveChanges();

}
//else
//{
//    ViewBag.msg = "Please upload .jpg and .jpeg  file";
//}
//}
else
{
ViewBag.msg = "Please upload less than 10 kb";
}
ViewBag.msg = "Saved";
return View();
}
}
}

Source Code of Index.cshtml…………………………….

@model MvcApplication2.Models.EmployeeInfo

@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</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" />

@*  <form action="" method="post" enctype="multipart/form-data" >*@

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

{
@Html.ValidationSummary(true)

<fieldset>
<legend>Employee</legend>

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

<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.Age)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Age)
@Html.ValidationMessageFor(model => model.Age)
</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.EditorFor(model => model.Password)*@
@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.EditorFor(model => model.ConfirmPassword)*@
@Html.PasswordFor(model=>model.ConfirmPassword)
@Html.ValidationMessageFor(model => model.ConfirmPassword)
</div>

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

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

<div class="editor-label">
@Html.LabelFor(model => model.UserImage)
</div>
<div class="editor-field">
@* @Html.EditorFor(model => model.UserImage)
@Html.ValidationMessageFor(model => model.UserImage)*@
<input type="file" name="UserImage" id="file" />
</div>

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

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

<p>

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

<div>
@Html.ActionLink("Back to List", "Index")
</div>
</body>
</html>

Result




0 comments:

Post a Comment