Introduction :
In this article we are going to create employee Registration form, which containd filed like textbox, image upload using Jquery and ajax using mvc5 with sql server database, Mvc 5 Registration form with image upload.
mvc 5 registration form with image upload
First Create Sql server database and also create table Employee :
CREATE TABLE [dbo].[Employee]( [UserID] [int] IDENTITY(1,1) NOT NULL, [UserName] [nvarchar](50) NULL, [City] [nvarchar](50) NULL, [State] [nvarchar](50) NULL, [Mobile] [nvarchar](50) NULL, [Profile] [nvarchar](50) NULL, [ProfileImage] [varchar](100) NULL, CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED ( [UserID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO
Create Store Procedure for insert update delete
/****** StoredProcedure For Insert Update ******/ Create PROCEDURE [dbo].[Employee_InsertUpdate] @UserID int=0, @UserName nvarchar(50), @City nvarchar(50)='' , @State nvarchar(50)='' , @Mobile nvarchar(50)='' , @Profile nvarchar(50)='' AS IF(@UserID>0) BEGIN update Employee set UserName=@UserName,City=@City,State=@State,Mobile=@Mobile,Profile=(case when @Profile='' then Profile else @Profile end) where userid=@UserID END ELSE BEGIN Insert into Employee (UserName,City,State,Mobile,Profile) VALUES (@UserName,@City,@State,@Mobile,@Profile) END /****** Store procedure for select ******/ Create PROCEDURE [dbo].[EMPLOYEE_SELECT] @UserID int =0 AS if(@UserID>0) begin select * from Employee where UserID=@UserID end else begin select * from Employee end /****** SP For Delete Record ******/ CREATE PROCEDURE [dbo].[Employee_Delete] @UserID int=0 AS IF(@UserID>0) BEGIN delete from Employee where UserID=@UserID END /****** StoredProcedure For EMPLOYEE_Filter ******/ CREATE PROCEDURE [dbo].[EMPLOYEE_Filter] @Name NVARCHAR(64) ='', @City NVARCHAR(64) ='' AS begin IF ( @Name = '' ) SET @Name = NULL; IF ( @City = '' ) SET @City = NULL; select * from Employee em where ((ISNULL(em.UserName,'') LIKE '%' + @Name + '%' OR @Name IS NULL) ) AND (((ISNULL(em.City,'') LIKE '%' + @City + '%' OR @City IS NULL) )) end
Now create Sql connection from Web.config
<connectionStrings> <add name="myConnectionString" connectionString="server=MyPc;database=MVCR;Trusted_Connection=true;" /> </connectionStrings>
Now Create Action method for Registration form
AddEmployee.cshtml :
@model MVC_FileUpload.Models.EmployeeModel @{ ViewBag.Title = "FileUpload"; <fieldset> <input type="hidden" class="form-control" id="txtuserID" value="@(Model != null ? Model.UserID:0)" /> <legend>Register New Employee </legend> <div class="form-group"> <label for="txtName">Name</label> <input type="text" class="form-control" id="txtName" value="@(Model != null ? Model.UserName:"")" placeholder="Name" /> </div> <div class="form-group"> <label for="txtstate">State</label> <input type="text" class="form-control" id="txtstate" value="@(Model != null ? Model.State:"")" placeholder="state" /> </div> <div class="form-group"> <label for="txtcity">City</label> <input type="text" class="form-control" id="txtcity" value="@(Model != null ? Model.City:"")" placeholder="City" /> </div> <div class="form-group"> <label for="txtphone">Phone</label> <input type="text" class="form-control" id="txtphone" value="@(Model != null ? Model.Mobile:"")" placeholder="Phone" /> </div> <div class="form-group"> <label for="fileupload">Profile Picture</label> <input type="file" class="form-control" id="fileupload" /> </div> <div class="form-group"> <input type="button" id="btnregistered" value="Register" /> </div> </fieldset> }
@section scripts{ <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script> $(document).ready(function () { $('#btnregistered').click(function () { if (window.FormData !== undefined) { var res = ValidateForm(); if (res == false) { return false; } var fileUpload = $("#fileupload").get(0); var files = fileUpload.files; var fileData = new FormData(); fileData.append('FullName', $("#txtName").val()); fileData.append('state', $("#txtstate").val()); fileData.append('city', $("#txtcity").val()); fileData.append('phone', $("#txtphone").val()); fileData.append('userid', $("#txtuserID").val()); for (var i = 0; i < files.length; i++) { fileData.append(files[i].name, files[i]); } $.ajax({ url: '/Home/AddEmployeePost', type: "POST", contentType: false, processData: false, data: fileData, success: function (result) { alert(result); window.location.href = "/home/Index"; }, error: function (err) { alert(err.statusText); } }); } else { alert("Your browser doesn support FormData"); } }); function ValidateForm() { var isValid = true; if ($('#txtName').val().trim() == "") { $('#txtName').css('border-color', 'Red'); isValid = false; } else { $('#txtName').css('border-color', 'lightgrey'); } if ($('#txtstate').val().trim() == "") { $('#txtstate').css('border-color', 'Red'); isValid = false; } else { $('#txtstate').css('border-color', 'lightgrey'); } if ($('#txtcity').val().trim() == "") { $('#txtcity').css('border-color', 'Red'); isValid = false; } else { $('#txtcity').css('border-color', 'lightgrey'); } if ($('#txtphone').val().trim() == "") { $('#txtphone').css('border-color', 'Red'); isValid = false; } else { $('#txtphone').css('border-color', 'lightgrey'); } return isValid; } }); </script> }
ADD/Update Employee :
Action Method :
// Add and update Employee [HttpGet] public ActionResult AddEmployee(int id=0) { if (id > 0) { EmployeeRepository sr = new EmployeeRepository(); return View(sr.GetEmployee(id)); } else { return View(); } } [HttpPost] public ActionResult AddEmployeePost() { try { int userid = Convert.ToInt32(Request.Form["userid"]); string FullName = Request.Form["FullName"]; string state = Request.Form["state"]; string city = Request.Form["city"]; string phone = Request.Form["phone"]; EmployeeModel emp = new EmployeeModel(); emp.UserName = FullName; emp.State = state; emp.City = city; emp.Mobile = phone; emp.UserID = userid; EmployeeRepository sr = new EmployeeRepository(); if (Request.Files.Count > 0) { try { HttpPostedFileBase file = Request.Files[0]; string fname = file.FileName; string path = Server.MapPath("/Content/Images/"); string st = path + fname; file.SaveAs(path+fname); emp.Profile = fname; } catch (Exception ex) { return Json(ex.Message); } } sr.AddUpdateEmployee(emp); } catch (Exception e) { ModelState.AddModelError("", e.Message); } return Json("success!"); } // Edit View public ActionResult EditEmployee(int id = 0, string filename = "") { EmployeeRepository sr = new EmployeeRepository(); return View(sr.GetEmployee(id)); }
Add View For select employee Index.cshtml :
@using (Ajax.BeginForm("EmployeeList", "Home", new AjaxOptions { OnSuccess = "GetRecords", OnBegin = "", OnComplete = "" }, new { @id = "frmOrdgrid" })) { <p> @Html.ActionLink("Add New Employee", "AddEmployee") <br /> <table> <tr> <td>Name:</td> <td>@Html.TextBox("username")</td> </tr> <tr> <td>City:</td> <td>@Html.TextBox("city")</td> </tr> <tr> <td></td> <td><input type="submit" id="SearchBtn" value="Search" /></td> </tr> </table> <br /> </p> } <br /> <div id="dvEmployeeList"> </div> @section scripts{ <script src="~/Scripts/jquery.validate.unobtrusive.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ajax-unobtrusive/3.2.6/jquery.unobtrusive-ajax.min.js"></script> <script> $("#frmOrdgrid").submit(); function GetRecords(data) { if (data != '\r\n') { if ($("#dvEmployeeList").length > 0) $("#dvEmployeeList").html(data); } } </script> }
Add Partial View : _EmployeeList.cshtml
@model IEnumerable<MVC_FileUpload.Models.EmployeeModel> <table class="table"> <thead> <tr> <th> @Html.DisplayNameFor(model => model.UserName) </th> <th> @Html.DisplayNameFor(model => model.City) </th> <th> @Html.DisplayNameFor(model => model.State) </th> <th> @Html.DisplayNameFor(model => model.Mobile) </th> <th> @Html.DisplayNameFor(model => model.Profile) </th> <th></th> </tr> </thead> <tbody > @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.UserName) </td> <td> @Html.DisplayFor(modelItem => item.City) </td> <td> @Html.DisplayFor(modelItem => item.State) </td> <td> @Html.DisplayFor(modelItem => item.Mobile) </td> <td> <img src="~/Content/Images/@item.Profile" height="50" width="50"/> </td> <td> @Html.ActionLink("Edit", "AddEmployee", new { id = item.UserID, filename = @item.Profile }) | @Html.ActionLink("Delete", "DeleteEmployee", new { id = item.UserID,filename= @item.Profile }) </td> </tr> } </tbody> </table>
Now add code for delete action method and Partialview :
public ActionResult DeleteEmployee(int id = 0,string filename="") { EmployeeRepository sr = new EmployeeRepository(); sr.DeleteEmployee(id); if (id > 0 && !string.IsNullOrEmpty(filename)) { var filePath = Server.MapPath("/Content/Images/" + filename); if (System.IO.File.Exists(filePath)) { System.IO.File.Delete(filePath); } } return RedirectToAction("Index"); } [HttpPost] public ActionResult EmployeeList(FormCollection collection) { EmployeeRepository sr = new EmployeeRepository(); string stName = collection["username"]; string stCity = collection["city"]; return PartialView("_EmployeeList", sr.GetFilterEmployee(stName, stCity)); }
Adding code for database operation :
Create model class : EmployeeModel
public class EmployeeModel { public int UserID { get; set; } public string UserName { get; set; } public string City { get; set; } public string State { get; set; } public string Mobile { get; set; } public string Profile { get; set; } }
Now Add Folder: Repository and add class: EmployeeRepository.cs
public class EmployeeRepository { string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString; public EmployeeModel AddUpdateEmployee(EmployeeModel em) { using (var con = new SqlConnection(connStr)) { try { SqlCommand cmd; con.Open(); cmd = new SqlCommand("Employee_InsertUpdate", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@UserID", em.UserID); cmd.Parameters.AddWithValue("@UserName", em.UserName); cmd.Parameters.AddWithValue("@City", em.City); cmd.Parameters.AddWithValue("@State", em.State); cmd.Parameters.AddWithValue("@Mobile", em.Mobile); cmd.Parameters.AddWithValue("@Profile", em.Profile); cmd.ExecuteNonQuery(); con.Close(); return em; } catch (Exception) { throw; } } } public void DeleteEmployee(int id) { try { using (var con = new SqlConnection(connStr)) { SqlCommand cmd; con.Open(); cmd = new SqlCommand("Employee_Delete", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@UserID", id); cmd.ExecuteNonQuery(); con.Close(); } } catch (Exception) { throw; } } public List<EmployeeModel> GetAllEmployee() { try { using (var con = new SqlConnection(connStr)) { DataTable dt = new DataTable(); SqlDataAdapter adp = new SqlDataAdapter("EMPLOYEE_SELECT", con); adp.Fill(dt); List<EmployeeModel> lst = new List<EmployeeModel>(); foreach (DataRow dr in dt.Rows) { EmployeeModel em = new EmployeeModel(); em.UserID = Convert.ToInt32(dr["UserID"]); em.UserName = Convert.ToString(dr["UserName"]); em.Mobile = Convert.ToString(dr["Mobile"]); em.Profile = Convert.ToString(dr["Profile"]); em.State = Convert.ToString(dr["State"]); em.City = Convert.ToString(dr["City"]); lst.Add(em); } return lst; } } catch (Exception) { throw; } } public EmployeeModel GetEmployee(int id) { try { using (var con = new SqlConnection(connStr)) { EmployeeModel em = new EmployeeModel(); con.Open(); SqlCommand cmd = new SqlCommand("EMPLOYEE_SELECT", con); cmd.Parameters.AddWithValue("UserID", id); cmd.CommandType = CommandType.StoredProcedure; SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { em.UserID = Convert.ToInt32(dr["UserID"]); em.UserName = Convert.ToString(dr["UserName"]); em.Mobile = Convert.ToString(dr["Mobile"]); em.Profile = Convert.ToString(dr["Profile"]); em.State = Convert.ToString(dr["State"]); em.City = Convert.ToString(dr["City"]); } con.Close(); return em; } } catch (Exception) { throw; } } public List<EmployeeModel> GetFilterEmployee(string name, string city) { try { using (var con = new SqlConnection(connStr)) { con.Open(); SqlCommand cmd = new SqlCommand("EMPLOYEE_Filter", con); cmd.Parameters.AddWithValue("Name", name); cmd.Parameters.AddWithValue("City", city); cmd.CommandType = CommandType.StoredProcedure; SqlDataReader dr = cmd.ExecuteReader(); List<EmployeeModel> list = new List<EmployeeModel>(); while (dr.Read()) { EmployeeModel em = new EmployeeModel(); em.UserID = Convert.ToInt32(dr["UserID"]); em.UserName = Convert.ToString(dr["UserName"]); em.Mobile = Convert.ToString(dr["Mobile"]); em.Profile = Convert.ToString(dr["Profile"]); em.State = Convert.ToString(dr["State"]); em.City = Convert.ToString(dr["City"]); list.Add(em); } con.Close(); return list; } } catch (Exception) { throw; } } }
ScreenShot :
Filter Employee List by Name and City :
Edit Employee Data :