Thursday, 28 January 2016


Hello friend's I will like to share some annoying error I have faced in MVC and finally after lot of google search I found the solution

{"Method not found: 'System.Web.Routing.RouteValueDictionary System.Web.WebPages.TypeHelper.ObjectToDictionaryUncached(System.Object)'."}


Dev's Blog
Solution:

It seems that there is an error in MVC routing but the main culprit was 

System.Web.MVC and System.Web.WebPages

Just delete it from existing solution and reinstall from nuget.
Check the version is web.config file
Clean the solution & build and run.

This works for me. Hope it works for you to.

Wednesday, 27 January 2016

MVC : Ajax Gridview Paging / Search / Export to Excel

Hello friends, Welcome to my blog.  In this post I will do an small project on grid view paging, search and export to excel using Ajax and MVC 5. I will start from creating database in SQL Server 2014.

Step 1:

Create table CustomerDetail and insert large data in it.
CREATE TABLE CustomerDetail
(
ID BIGINT PRIMARY KEY IDENTITY(1,1),
FullName VARCHAR(500),
Age INT,
Gender VARCHAR(500),
CreatedDate DATETIME DEFAULT(GETDATE())
)

--To Fill data in the above created table use this script

DECLARE @i INT, @gender VARCHAR(500)
SET @i=1
WHILE(@i <= 506)
BEGIN
 IF(@i % 2 = 0)
  SET @gender = 'Female'
 ELSE
  SET @gender = 'Male'
 
 INSERT INTO CustomerDetail(FullName,Age,Gender)
 VALUES ('Full Name '+ CONVERT(VARCHAR(500), @i) , FLOOR(RAND(CHECKSUM(NEWID()))*(18-100)+100), @gender)

 SET @i = @i + 1
END 

FLOOR(RAND(CHECKSUM(NEWID()))*(18-100)+100)
this code is used to generate random age between 18 and 100.

Step 2:

Create a folder called Data in this folder use ADO.Net Entity Framework and connect with database. You can check my previous post here.

Now add class "CustomerDetailRepository" this class is responsible for communicating between UI and database with entity framework
public class CustomerDetailRepository
    {
        public CustomerDetailRepository() { }

        public List GetListOfCustomer(int page, int pageSize, string Search, out int totalRecord, out int totalPage)
        {
            List objLstCD = new List();
            IEnumerable IDCount;
            IEnumerable IData;

            using (RegistrationDemoEntities dbContext = new RegistrationDemoEntities())
            {
                try
                {
                    if (!string.IsNullOrEmpty(Search))
                    {
                        IDCount = (from cd in dbContext.CustomerDetails
                                   where cd.FullName.Contains(Search) || cd.Gender == Search
                                   select cd.ID);

                        IData = (from cd in dbContext.CustomerDetails
                                 where cd.FullName.Contains(Search) || cd.Gender == Search
                                 select new CustomerDetailModel
                                 {
                                     ID = cd.ID,
                                     FullName = cd.FullName,
                                     Age = cd.Age,
                                     Gender = cd.Gender,
                                     CreatedDate = cd.CreatedDate
                                 }).OrderBy(x => x.ID).Skip((page - 1) * pageSize).Take(pageSize);
                    }
                    else
                    {
                        IDCount = (from cd in dbContext.CustomerDetails
                                   select cd.ID);

                        IData = (from cd in dbContext.CustomerDetails
                                 select new CustomerDetailModel
                                 {
                                     ID = cd.ID,
                                     FullName = cd.FullName,
                                     Age = cd.Age,
                                     Gender = cd.Gender,
                                     CreatedDate = cd.CreatedDate
                                 }).OrderBy(x => x.ID).Skip((page - 1) * pageSize).Take(pageSize);
                    }

                    totalRecord = Convert.ToInt32(IDCount.ToList().Count());
                    totalPage = (totalRecord / pageSize) + ((totalRecord % pageSize) > 0 ? 1 : 0);

                    foreach (var item in IData)
                    {
                        objLstCD.Add(new CustomerDetailModel()
                        {
                            ID = item.ID,
                            FullName = item.FullName,
                            Age = item.Age,
                            Gender = item.Gender,
                            CreatedDate = (DateTime)item.CreatedDate,
                        });
                    }
                }
                catch (Exception Ex) { throw Ex; }
            }
            return objLstCD;
        }

        public List ExportToExcelListOfCustomer()
        {
            List objLstCD = new List();
            IEnumerable IData;

            using (RegistrationDemoEntities dbContext = new RegistrationDemoEntities())
            {
                try
                {
                    IData = (from cd in dbContext.CustomerDetails
                             select new CustomerDetailModel
                             {
                                 ID = cd.ID,
                                 FullName = cd.FullName,
                                 Age = cd.Age,
                                 Gender = cd.Gender,
                                 CreatedDate = cd.CreatedDate
                             });

                    foreach (var item in IData)
                    {
                        objLstCD.Add(new CustomerDetailModel()
                        {
                            ID = item.ID,
                            FullName = item.FullName,
                            Age = item.Age,
                            Gender = item.Gender,
                            CreatedDate = item.CreatedDate
                        });
                    }
                }
                catch (Exception Ex) { throw Ex; }
            }
            return objLstCD;
        }
    }

Step 3:

In model folder create CustomerDetailModel class.
public class CustomerDetailModel
    {
        public long ID { get; set; }
        public string FullName { get; set; }
        public Nullable Age { get; set; }
        public string Gender { get; set; }
        public Nullable CreatedDate { get; set; }
    }

Step 4:

In Data folder create PagerRespository class. This class is use to generate paging for the grid.
public class PagerRespository
    {
        #region "Properties"
        public int TotalItems { get; private set; }
        public int CurrentPage { get; private set; }
        public int PageSize { get; private set; }
        public int TotalPages { get; private set; }
        public int StartPage { get; private set; }
        public int EndPage { get; private set; }

        public string PagerHtmlCode { get; set; }
        #endregion

        public PagerRespository(int totalItems, int? page, int pageSize)
        {
            // calculate total, start and end pages
            var totalPages = (int)Math.Ceiling((decimal)totalItems / (decimal)pageSize);
            var currentPage = page != null ? (int)page : 1;
            var startPage = currentPage - 5;
            var endPage = currentPage + 4;

            if (startPage <= 0)
            {
                endPage -= (startPage - 1);
                startPage = 1;
            }

            if (endPage > totalPages)
            {
                endPage = totalPages;
                if (endPage > 10)
                {
                    startPage = endPage - 9;
                }
            }

            TotalItems = totalItems;
            CurrentPage = currentPage;
            PageSize = pageSize;
            TotalPages = totalPages;
            StartPage = startPage;
            EndPage = endPage;
            PagerHtmlCode = GeneratePagerHtmlCode();
        }

        public string GeneratePagerHtmlCode()
        {
            string CssClass = "active";
            StringBuilder sb = new StringBuilder();
            if (EndPage > 1)
            {
                sb.Append("
    "); if (CurrentPage > 1) { int iPreviousPage = CurrentPage - 1; sb.Append("
  • "); sb.Append(" First "); sb.Append("
  • "); sb.Append("
  • "); sb.Append(" Previous "); sb.Append("
  • "); } for (var page = StartPage; page <= EndPage; page++) { if (page != CurrentPage) CssClass = ""; sb.Append("
  • "); sb.Append(" " + page.ToString() + " "); sb.Append("
  • "); } if (CurrentPage < TotalPages) { int iNextPage = CurrentPage + 1; sb.Append("
  • "); sb.Append(" Next "); sb.Append("
  • "); sb.Append("
  • "); sb.Append(" Last "); sb.Append("
  • "); } sb.Append("
"); } return sb.ToString(); } }

Step 5:

Create ViewModel folder and add CustomerDetailVM class.
public class CustomerDetailVM
    {
        public IEnumerable CustomerDetailList { get; set; }
        public PagerRespository Pager { get; set; }
    }

Step 6:

Create CustomerDetailController class in your Controllers folder.
using System;
using System.Web.Mvc;
using RegistrationDemoApp.Data;
using RegistrationDemoApp.ViewModel;
using RegistrationDemoApp.Models;
using System.Collections.Generic;
using System.Data;

namespace RegistrationDemoApp.Controllers
{
    public class CustomerDetailController : Controller
    {
        CustomerDetailRepository objCR = null;

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

        [HttpPost]
        public JsonResult Index(string pageNumber, string pageSizeVal, string Search)
        {   
            int totalPage = 0;
            int totalRecord = 0;
            int pageSize = Convert.ToInt32(pageSizeVal);
            int page = string.IsNullOrEmpty(pageNumber) ? 1 : Convert.ToInt32(pageNumber);

            objCR = new CustomerDetailRepository();
            var CDLst = objCR.GetListOfCustomer(page, pageSize, Search, out totalRecord, out totalPage);

            var pagerData = new PagerRespository(totalRecord, page, pageSize);
            var objCustomerDetailVM = new CustomerDetailVM
            {
                CustomerDetailList = CDLst,
                Pager = pagerData
            };

            return Json(objCustomerDetailVM, JsonRequestBehavior.AllowGet);
        }

        public ActionResult ExportDataToExcel()
        {
            objCR = new CustomerDetailRepository();
            List objLstCD = objCR.ExportToExcelListOfCustomer();

            DataTable DT = UtilitiesFile.ConvertToDatatable(objLstCD);
            string FileName = UtilitiesFile.GetGenerateExcelFile("CustomerDetails", DT);
            return RedirectToAction("Index");
        }
    }
}

Step 7:

Now right click on Index action method and select "Add View". Keep the name as it is and make sure in Template dropdown menu 'Empty (without model)' is selected after that a "Index.cshtml" file will be generated in Views >> CustomerDetail folder. Check the view code mention below.
Gridview Paging / Search / Export to Excel
@Html.DropDownList("DDL_PageSize", new SelectList(new Dictionary { { "10", 10 }, { "25", 25 }, { "50", 50 }, { "100", 100 } }, "Key", "Value", "10"), new { @class = "form-control-static", id = "DDL_PageSize" })
ID Full Name Age Gender Created Date

Step 8:

Now add jquery code in you view, if you wish you can add it in separate js file and link to view.



Step 9:

I have used EPPlus from codeplex to generate excel sheet. You can find it from here. Download the files & right click on solution to add reference of EPPlus to your project.

Step 10:

Create "UtilitiesFile.cs" class in data folder. This file will generate and download excel file. Check the code below.
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;

namespace RegistrationDemoApp.Data
{
    public class UtilitiesFile
    {
        public UtilitiesFile() { }

        #region "Generate Excel File using EPP class"
        public static string GetGenerateExcelFile(string strAppendText, DataTable DT)
        {
            string FullPath = "", strFileName = "";
            try
            {
                strFileName = strAppendText + DateTime.Now.ToString("ddMMMyyyyHHmmssfff") + ".xlsx";
                string FilePath = HttpContext.Current.Server.MapPath("~/DownloadedFiles/");
                DirectoryInfo DirInfo = new DirectoryInfo(FilePath);
                if (!DirInfo.Exists)
                    Directory.CreateDirectory(FilePath);

                FullPath = FilePath + strFileName;
                FileInfo FInfo = new FileInfo(FullPath);
                using (ExcelPackage xlPackage = new ExcelPackage(FInfo))
                {
                    ExcelWorksheet workSheet = xlPackage.Workbook.Worksheets.Add(strAppendText);

                    if (DT.Rows.Count > 0)
                    {
                        for (int j = 0; j <= DT.Rows.Count - 1; j++)
                        {
                            for (int k = 0; k <= DT.Columns.Count - 1; k++)
                            {
                                if (j == 0)
                                {
                                    workSheet.Cells[1, k + 1].Value = Convert.ToString(DT.Columns[k]); //For Column Header
                                    workSheet.Cells[1, k + 1].Style.Font.Bold = true;
                                }

                                workSheet.Cells[2 + j, k + 1].Value = Convert.ToString(DT.Rows[j][k]); //For Column Cell Value                                
                            }
                        }

                        xlPackage.Save();

                        HttpContext.Current.Response.Clear();
                        HttpContext.Current.Response.Buffer = true;
                        HttpContext.Current.Response.Charset = "";
                        HttpContext.Current.Response.ContentType = "application/ms-excel";
                        HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + strFileName);
                        HttpContext.Current.Response.WriteFile(FullPath);
                        HttpContext.Current.Response.Flush();
                        HttpContext.Current.Response.End();
                    }
                }
            }
            catch (Exception Ex) { throw Ex; }
            return strFileName;
        }
        #endregion

        #region "ListToDatatable"
        public static DataTable ConvertToDatatable(IEnumerable data)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
            DataTable table = new DataTable();

            foreach (PropertyDescriptor prop in properties)
                table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
            foreach (T item in data)
            {
                DataRow row = table.NewRow();
                foreach (PropertyDescriptor prop in properties)
                {
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                }
                table.Rows.Add(row);
            }
            return table;
        }
        #endregion
    }
}

Step 11:

Now run the application and check the output.

Thanks for reading, I appreciate your comments & feedback.

Tuesday, 12 January 2016

Remote Validation MVC

Hello friends, Welcome to my blog. In this post I will do an small project on data annotations with remote validation using MVC 5. I will start from creating database in SQL Server 2014.

Step 1:

Create table RegisterUser and DesiginationMaster, the purpose of "DesiginationMaster" table is to fill dropdown menu and validate it using data annotation. So instead of static values I have created table.
create table RegisterUser
(
ID BIGINT PRIMARY KEY IDENTITY(1,1),
FullName VARCHAR(500),
Gender VARCHAR(500),
EmailID VARCHAR(500),
MobileNumber VARCHAR(500),
Desigination VARCHAR(500),
UserName VARCHAR(500),
[Password] VARCHAR(500),
UploadFile VARCHAR(500),
CreatedDate DATETIME DEFAULT(GETDATE()),
IsActive BIT DEFAULT(1)
)

create table DesiginationMaster
(
ID INT PRIMARY KEY IDENTITY(1,1),
Desigination VARCHAR(500)
)

insert into DesiginationMaster(Desigination) values ('Jr Programmer')
insert into DesiginationMaster(Desigination) values ('Sr Programmer')
insert into DesiginationMaster(Desigination) values ('Project Leader')
insert into DesiginationMaster(Desigination) values ('Project Manager')
insert into DesiginationMaster(Desigination) values ('Sr Project Manager')
insert into DesiginationMaster(Desigination) values ('Director')

Step 2:

Follow the images below to create project using visual studio 2015




Step 3:

After creating project add a folder called "Data" for Entity Framework. Follow the images below.


Step 4:

Now we will add & configure our entity framework in "Data" folder.


Step 5:

Now add "RegisterUserModel.cs" in our model folder. Map each property with data annotations validation attributes. A custom attribute "FileExtensionValidation" is created for file upload for server side validation.
using System;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using RegistrationDemoApp.CustomAttribute;

namespace RegistrationDemoApp.Models
{
    public class RegisterUserModel
    {
        [Key]
        public long ID { get; set; }

        [Required(ErrorMessage = "Full Name Is Required.")]
        [RegularExpression(@"^[a-zA-Z'' ']+$", ErrorMessage = "Full Name Cannot Contain Special Character Other Than Space & Numbers.")]
        [StringLength(100)]
        public string FullName { get; set; }

        [Required(ErrorMessage = "Gender Is Required.")]
        public string Gender { get; set; }

        [Required(ErrorMessage = "Email ID Is Required.")]
        [EmailAddress(ErrorMessage = "Invalid Email Address")]
        [Remote("IsEmailIDExist", "Home", ErrorMessage = "Email Address already exists.")]
        public string EmailID { get; set; }

        [Required(ErrorMessage = "Mobile Number Is Required.")]
        [RegularExpression(@"[0-9]*\.?[0-9]+", ErrorMessage = "Only Numbers Allowed.")]
        [StringLength(10, ErrorMessage = "Mobile Number Should Be 10 Digit.", MinimumLength = 10)]
        public string MobileNumber { get; set; }

        [Required(ErrorMessage = "Desigination Is Required.")]
        public string Desigination { get; set; }

        [Required(ErrorMessage = "User Name Is Required.")]
        [RegularExpression(@"^[a-zA-Z0-9]+$", ErrorMessage = "User Name Cannot Contain Special Charater.")]
        [Remote("IsUserNameExist", "Home", ErrorMessage = "User Name already exists.")]
        public string UserName { get; set; }

        [Required(ErrorMessage = "Password Is Required.")]
        [StringLength(10, ErrorMessage = "Password Should Be 5 to 10 Characters.", MinimumLength = 5)]
        public string Password { get; set; }

        [Required(ErrorMessage = "Please Upload File.")]
        [FileExtensionValidation(".doc,.docx,.pdf")]
        public HttpPostedFileBase UploadFile { get; set; }

        public DateTime CreatedDate { get; set; }

        public bool IsActive { get; set; }
    }
}
Create a folder called "CustomAttribute" and add a file called "FileExtensionValidation.cs".

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

namespace RegistrationDemoApp.CustomAttribute
{
    public class FileExtensionValidation:ValidationAttribute
    {
        string[] sAllowedExtension = new string[] { };
        public FileExtensionValidation(string Extensions)
        {
            sAllowedExtension = Extensions.Split(',');
        }
        public override bool IsValid(object value)
        {
            int iLength = 1024 * 1024; //1 MB
            var file = value as HttpPostedFileBase;
            if (file == null) return false;
            else if (!sAllowedExtension.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
            {
                ErrorMessage = "Only " + string.Join(", ", sAllowedExtension) + " is allowed.";
                return false;
            }
            else if (file.ContentLength > iLength)
            {
                ErrorMessage = "Your file is too large to upload only 1MB is allowed.";
                return false;
            }
            else
                return true;
        }
    }
}

Step 6:

We will be using multiple model in a single view so to achieve this add a folder called "ViewModel" and add class "RegisterUserVM" in it. Note we cannot use multiple model in same view, so a new class is created which holds the definition of the multiple classes which are going to be used in a view they are nothing but viewmodel class.

using RegistrationDemoApp.Models;
using System.Collections.Generic;
using System.Web.Mvc;

namespace RegistrationDemoApp.ViewModel
{
    public class RegisterUserVM
    {
        public RegisterUserVM() {}

        public RegisterUserModel RegisterUserModel { get; set; }

        //This will be used for binding register user record to gridview but not used in this post.
        public List RegisterUserModelList { get; set; } 

        public IEnumerable DesiginationMasterModelLst { get; set; }
    }
}

Step 7:

Now in home controller add the following action methods called "RegisterUser" & "RegisterUserData" to fill dropdown menu and to create new user respectively.


       //fill designation dropdown  menu
        public ActionResult RegisterUser()
        {
            RegisterUserVM objRUVM = new RegisterUserVM();

            using (RegistrationDemoEntities db = new RegistrationDemoEntities())
            {
                var DMLst = db.DesiginationMasters.ToList();

                objRUVM.DesiginationMasterModelLst = (from a in DMLst
                                                      select new SelectListItem
                                                      {
                                                          Value = a.ID.ToString(),
                                                          Text = a.Desigination
                                                      });
            }
            return View(objRUVM);
        }

        //create user
        public ActionResult RegisterUserData(RegisterUserVM objRUVM)
        {
            string Status = "";
            if (ModelState.IsValid)
            {
                Status = RegisterUserRepository.SaveRegisterUser(objRUVM);
                ModelState.Clear();
            }
            else
            {
                var Error = ModelState.Values.SelectMany(x => x.Errors).ToList();
                foreach (var item in Error)
                {
                    Status += "Error : " + item.ErrorMessage;
                }
            }

            if (Status == "success")
                TempData["Status"] = "Record Saved Successfully.";
            else if (Status == "fail")
                TempData["Status"] = "Fail To Save Record.";
            else
                TempData["Status"] = Status;

            return RedirectToAction("RegisterUser", "Home");
        }

        //Remote validation Functions
        public JsonResult IsUserNameExist(RegisterUserVM objRUVM)
        {
            bool Status = RegisterUserRepository.IsUserNameValid(objRUVM);
            return Json(Status, JsonRequestBehavior.AllowGet);
        }

        public JsonResult IsEmailIDExist(RegisterUserVM objRUVM)
        {
            bool Status = RegisterUserRepository.IsEmailIDValid(objRUVM);
            return Json(Status, JsonRequestBehavior.AllowGet);
        }
        //Remote validation Functions


Step 8:

Now add view for "RegisterUserData". To do so keep cursor anywhere within "RegisterUserData" action right click & select "Add View". Keep the name as it is and make sure in Template dropdown menu 'Empty (without model)' is selected after that a "RegisterUserData.cshtml" file will be generated in Views >> Home folder. Check the view code mention below.
@model RegistrationDemoApp.ViewModel.RegisterUserVM

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

Register User


@Html.Raw(TempData["Status"])
@Html.TextBoxFor(m => m.RegisterUserModel.FullName, htmlAttributes: new { id = "TxtFullName", @class = "form-control", placeholder = "Full Name" }) @Html.ValidationMessageFor(model => model.RegisterUserModel.FullName, "", new { @class = "text-danger" })
@Html.LabelFor(m=> m.RegisterUserModel.Gender) : @Html.Label("Male") @Html.RadioButtonFor(m => m.RegisterUserModel.Gender, "Male") @Html.Label("Female") @Html.RadioButtonFor(m => m.RegisterUserModel.Gender, "Female")
@Html.ValidationMessageFor(model => model.RegisterUserModel.Gender, "", new { @class = "text-danger" })
 
@Html.TextBoxFor(m => m.RegisterUserModel.EmailID, htmlAttributes: new { id = "TxtEmailID", @class = "form-control", placeholder = "Email ID" }) @Html.ValidationMessageFor(model => model.RegisterUserModel.EmailID, "", new { @class = "text-danger" })
@Html.TextBoxFor(m => m.RegisterUserModel.MobileNumber, htmlAttributes: new { id = "TxtMobileNumber", @class = "form-control", placeholder = "Mobile Number", maxlength=10 }) @Html.ValidationMessageFor(model => model.RegisterUserModel.MobileNumber, "", new { @class = "text-danger" })
 
@Html.DropDownListFor(m => m.RegisterUserModel.Desigination, Model.DesiginationMasterModelLst, "Select Desigination", new { id = "DDLDesigination", @class = "form-control" }) @Html.ValidationMessageFor(model => model.RegisterUserModel.Desigination, "", new { @class = "text-danger" })
@Html.TextBoxFor(m => m.RegisterUserModel.UserName, htmlAttributes: new { id = "TxtUserName", @class = "form-control", placeholder = "User Name" }) @Html.ValidationMessageFor(model => model.RegisterUserModel.UserName, "", new { @class = "text-danger" })
 
@Html.TextBoxFor(m => m.RegisterUserModel.Password, htmlAttributes: new { id = "TxtPassword", @class = "form-control", placeholder = "Password", type = "password" }) @Html.ValidationMessageFor(model => model.RegisterUserModel.Password, "", new { @class = "text-danger" })
@Html.TextBoxFor(m => m.RegisterUserModel.UploadFile, htmlAttributes: new { id = "FlUploadFile", type = "file" }) @Html.ValidationMessageFor(model => model.RegisterUserModel.UploadFile, "", new { @class = "text-danger" })
 
}

Step 9:

Now add jquery code in you view, if you wish you can add it in separate js file and link to view.



Step 10:

Now go to data folder and add a class called 'RegisterUserRepository.cs' this class is responsible for communicating between UI and database with entity framework. Check the code below.
using RegistrationDemoApp.ViewModel;
using System;
using System.IO;
using System.Linq;
using System.Web;

namespace RegistrationDemoApp.Data
{
    public class RegisterUserRepository
    {
        public RegisterUserRepository() { }

        public static string SaveRegisterUser(RegisterUserVM objRUVM)
        {
            string Status = "fail";

            try
            {
                //Save File
                var fileName = Path.GetFileName(objRUVM.RegisterUserModel.UploadFile.FileName);
                string UploadPath = HttpContext.Current.Server.MapPath("~/Content/Upload");
                if (!Directory.Exists(UploadPath))
                    Directory.CreateDirectory(UploadPath);

                var path = Path.Combine(UploadPath, fileName);
                objRUVM.RegisterUserModel.UploadFile.SaveAs(path);

                using (RegistrationDemoEntities db = new RegistrationDemoEntities())
                {
                    RegisterUser objRU = new RegisterUser();
                    objRU.FullName = objRUVM.RegisterUserModel.FullName;
                    objRU.Gender = objRUVM.RegisterUserModel.Gender;
                    objRU.EmailID = objRUVM.RegisterUserModel.EmailID;
                    objRU.MobileNumber = objRUVM.RegisterUserModel.MobileNumber;
                    objRU.Desigination = objRUVM.RegisterUserModel.Desigination;
                    objRU.UserName = objRUVM.RegisterUserModel.UserName;
                    objRU.Password = objRUVM.RegisterUserModel.Password;
                    objRU.UploadFile = fileName;
                    objRU.CreatedDate = DateTime.Now;
                    objRU.IsActive = true;

                    db.RegisterUsers.Add(objRU);
                    db.SaveChanges();

                    Status = "success";
                }
            }
            catch (Exception Ex) { }

            return Status;
        }

        public static bool IsUserNameValid(RegisterUserVM objRUVM)
        {
            bool Status = false;
            using (RegistrationDemoEntities db = new RegistrationDemoEntities())
            {
                Status = db.RegisterUsers.Where(u => u.UserName == objRUVM.RegisterUserModel.UserName).ToList().Count() > 0 ? false : true;
            }
            return Status;
        }

        public static bool IsEmailIDValid(RegisterUserVM objRUVM)
        {
            bool Status = false;
            using (RegistrationDemoEntities db = new RegistrationDemoEntities())
            {
                Status = db.RegisterUsers.Where(u => u.EmailID == objRUVM.RegisterUserModel.EmailID).ToList().Count() > 0 ? false : true;
            }
            return Status;
        }
        
    }
}

Step 11:

Now run the application and check the output.








Thanks for reading, I appreciate your comments & feedback.