CRUD Operation With Image Insertion and Retrieval in ASP.Net MVC4 Through WCF

This application lets you perform CRUD operations on a table with an image column along with other text columns. The following is the structure for the table. Here we are using SQL Server 2008 as the BackEnd.

  1. create table Employee  
  2. (  
  3.     EmployeeId int identity(1,1),  
  4.     Name varchar(30),  
  5.     Address varchar(50),  
  6.     Department varchar(50),  
  7.     Photo varbinary(max)  
  8. )  
  9. insert into Employee(name,address,department) values('Vishal Gilbile','Andheri','IT')  
  10. insert into Employee(name,address,department) values('Rahul Bandekar','Worli','System')  
  11. insert into Employee(name,address,department) values('Jack Johnsens','Bandra','Oracle')  
  12. insert into Employee(name,address,department) values('Lolly Dolly','Dahisar','IT')  

This will add 4 rows to the table with all photo columns set to null.

Now we'll add the following procedures that we will be using to do the CRUD operations on the table.

  1. --for getting all the employees  
  2. create procedure prc_getallEmployees  
  3. as  
  4. begin  
  5. select * from Employee  
  6. end  
  7. --for adding a new employee  
  8. create procedure prc_addemployee  
  9. (  
  10. @name varchar(30),  
  11. @address varchar(50),  
  12. @department varchar(50),  
  13. @photo varbinary(max)= null  
  14. )  
  15. as  
  16. begin  
  17. insert into Employee values(@name,@address,@department,@photo)  
  18. end  
  19. --for updating the employee  
  20. create procedure prc_updateEmployee  
  21. (  
  22. @id int,  
  23. @name varchar(30),  
  24. @address varchar(50),  
  25. @department varchar(50),  
  26. @image varbinary(max)  
  27. )  
  28. as  
  29. begin  
  30. update Employee  
  31. set Name=@name,Address=@address,Department=@department,Photo=@image where EmployeeId=@id  
  32. end  
  33. --for deleting the Employee  
  34. create procedure prc_deleteEmployee  
  35. (  
  36. @eid int  
  37. )  
  38. as  
  39. begin  
  40. delete from Employee where EmployeeId=@eid  
  41. end 

We'll now move towards creation of the WCF service. Here we'll be creating a Service that will interact with the database to do the CRUD operations against the database table. For creation of the service we've made use of the WCF Service Library application that will provide us with a builtin hosting feature.

The following is the service description.

ServiceContract

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.ServiceModel;  
  6. using System.Text;  
  7. namespace CRUDService  
  8. {  
  9.     // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.  
  10.     [ServiceContract]  
  11.     public interface ICRUDOpr  
  12.     {  
  13.         [OperationContract]  
  14.         List<Employee> GetAllEmployees();  
  15.         [OperationContract]  
  16.         int AddEmployee(List<Employee> lstEmployee);  
  17.         [OperationContract]  
  18.         int UpdateEmployee(Employee objEmployee);  
  19.         [OperationContract]  
  20.         int DeleteEmployee(int eid);  
  21.     }  
  22. }

DataContract

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7. using System.Web.Mvc;  
  8. using System.ComponentModel.DataAnnotations;  
  9. namespace CRUDService  
  10. {  
  11.     [DataContract]  
  12.     public class Employee  
  13.     {  
  14.         [DataMember]  
  15.         public int EmployeeID { getset; }  
  16.         [DataMember]  
  17.         public string Name { getset; }  
  18.         [DataMember]  
  19.         public string Address { getset; }  
  20.         [DataMember]  
  21.         public string Department { getset; }  
  22.         [DataMember]  
  23.         public byte[] Photo { getset; }  
  24.     }  
  25. }  

Service

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.ServiceModel;  
  6. using System.Text;  
  7. using System.Data;  
  8. using System.Data.SqlClient;  
  9. using System.Configuration;  
  10. using System.Web;  
  11. namespace CRUDService  
  12. {  
  13.     // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in both code and config file together.  
  14.     public class CRUDOpr : ICRUDOpr  
  15.     {  
  16.         private string dbCon = ConfigurationManager.ConnectionStrings["myCon"].ConnectionString;  
  17.         SqlConnection con;  
  18.         SqlDataAdapter da;  
  19.         DataSet ds;  
  20.         SqlCommand cmd;  
  21.         public List<Employee> GetAllEmployees()  
  22.         {  
  23.             if (con == null)  
  24.                 con = new SqlConnection(dbCon);  
  25.             da = new SqlDataAdapter("prc_getallEmployees", con);  
  26.             da.SelectCommand.CommandType = CommandType.StoredProcedure;  
  27.             ds = new DataSet();  
  28.             da.Fill(ds);  
  29.             List<Employee> lstEmployee = new List<Employee>();  
  30.             if (ds.Tables.Count > 0)  
  31.             {  
  32.                 for (int i = 0; i < ds.Tables[0].Rows.Count; i++)  
  33.                 {  
  34.                     Employee obj = new Employee()  
  35.                     {  
  36.                         EmployeeID = Convert.ToInt32(ds.Tables[0].Rows[i]["EmployeeId"].ToString()),  
  37.                         Name = ds.Tables[0].Rows[i]["Name"].ToString(),  
  38.                         Address = ds.Tables[0].Rows[i]["Address"].ToString(),  
  39.                         Department = ds.Tables[0].Rows[i]["Department"].ToString(),  
  40.                         Photo = ds.Tables[0].Rows[i]["Photo"] == DBNull.Value ? null : (byte[])ds.Tables[0].Rows[i]["Photo"]  
  41.                     };  
  42.                     lstEmployee.Add(obj);  
  43.                 }  
  44.             }  
  45.             return lstEmployee;  
  46.         }  
  47.         public int AddEmployee(List<Employee> lstEmployee)  
  48.         {  
  49.             int rowsAffected = 0;  
  50.             if (con == null)  
  51.                 con = new SqlConnection(dbCon);  
  52.             cmd = new SqlCommand("prc_addemployee", con);  
  53.             cmd.CommandType = CommandType.StoredProcedure;  
  54.             con.Open();  
  55.             for (int i = 0; i < lstEmployee.Count; i++)  
  56.             {  
  57.                 cmd.Parameters.AddWithValue("@name", lstEmployee[i].Name);  
  58.                 cmd.Parameters.AddWithValue("@address", lstEmployee[i].Address);  
  59.                 cmd.Parameters.AddWithValue("@department", lstEmployee[i].Department);  
  60.                 cmd.Parameters.AddWithValue("@photo", lstEmployee[i].Photo);  
  61.                 rowsAffected += cmd.ExecuteNonQuery();  
  62.             }  
  63.             con.Close();  
  64.             return rowsAffected;  
  65.         }  
  66.         public int UpdateEmployee(Employee objEmployee)  
  67.         {  
  68.             int rowsAffected = 0;  
  69.             if (con == null)  
  70.                 con = new SqlConnection(dbCon);  
  71.             cmd = new SqlCommand("prc_updateEmployee", con);  
  72.             cmd.CommandType = CommandType.StoredProcedure;  
  73.             cmd.Parameters.AddWithValue("@id", objEmployee.EmployeeID);  
  74.             cmd.Parameters.AddWithValue("@name", objEmployee.Name);  
  75.             cmd.Parameters.AddWithValue("@address", objEmployee.Address);  
  76.             cmd.Parameters.AddWithValue("@department", objEmployee.Department);  
  77.             cmd.Parameters.AddWithValue("@image", objEmployee.Photo);  
  78.             con.Open();  
  79.             rowsAffected = cmd.ExecuteNonQuery();  
  80.             con.Close();  
  81.             return rowsAffected;  
  82.         }  
  83.         public int DeleteEmployee(int eid)  
  84.         {  
  85.             int rowsAffected = 0;  
  86.             if (con == null)  
  87.                 con = new SqlConnection(dbCon);  
  88.             cmd = new SqlCommand("prc_updateEmployee", con);  
  89.             cmd.CommandType = CommandType.StoredProcedure;  
  90.             cmd.Parameters.AddWithValue("@eid", eid);  
  91.             con.Open();  
  92.             rowsAffected = cmd.ExecuteNonQuery();  
  93.             con.Close();  
  94.             return rowsAffected;  
  95.         }  
  96.     }  
  97. }   

Note: Kindly check the App.Config of the WCF Service of this example after downloading the article.

Now our service is ready. We can start using it. Let's start creating the application by opening a new Visula Studio 2012 window and select the new project as MVC4 project. Provide the project name as ESoutions.

Run the service by pressing the F5 key. This will open the following dialog box, since we've used the WCF service library application.

the wcf service library application

Once the host is open we can add the service reference to our application. By right-clicking the ESolutions application then selecting the "Add Service Reference" option. Paste the URL that is shown in the preceding WCF Test client of your service, in my case the following is the URL:

http://localhost:8733/Design_Time_Addresses/CRUDService/CRUDOpr/mex

Provide the service reference name as Eservice and before proceeding further kindly check the web.config of your application; ensure that it contains the service reference tags or check the Reference.cs file of your Eservice Service Reference, that has been added to your MVC application. In my case these tags are not shown in the web.config file and my Reference.cs file is empty. The following is the snapshot of that.

Service Reference

This is because when I added the reference the DataContractSerializer class encountered a new type (Newtonsoft.Json.Linq.JToken) that it does not support and it throws an exception and stops creating the references. Now how to remove this error? Just a few simple steps are required. Right-click on your Eservice then click "Configure Service Reference". This will open the ServiceReferenceSettings dialog box as in the following:

ServiceReferenceSettings dialog box

Now select the radio button "Reuse types in referenced assemblies" then select all the checkboxes except Newtonsoft.JSon.

Newtonsoft.JSon

And click OK and now try to update the service reference. This time you'll find that References.cs is not empty and also there is any entry in the application web.config file for your service.

Note: If the Reference.cs in your case is not empty kindly ignore the preceding steps.

Once the service reference is added we can start with developing the application flow.

First we'll start the Model for our application. I create a new class with the name EmployeeViewModel inside my models folder. This class will have the same structure as the one we declared in the CRUDService DataContract class named Employee except for the Photo Property, there we took byte[] here we'll HttpPostedFileBase class; the reason will be explained later.

The following is the code for the EmployeeViewModel class with all the validation added as an attribute to the property.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.ComponentModel.DataAnnotations;  
  6. using System.Web.Mvc;  
  7. namespace ESolutions.Models  
  8. {  
  9.     public class EmployeeViewModel  
  10.     {  
  11.         [Key]//denotes that it uniquely identifies the employee  
  12.         public int EmployeeID { getset; }  
  13.         [Required(ErrorMessage="Name is Required")]  
  14.         public string Name { getset; }  
  15.         [Required(ErrorMessage="Address is Required")]  
  16.         public string Address { getset; }  
  17.         [Required(ErrorMessage="Department is Required")]  
  18.         public string Department { getset; }  
  19.         public HttpPostedFileBase Photo { getset; }  
  20.     }  
  21. } 

The next thing is to add a controller to our application. The following is the code for that.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using ESolutions.EService;  
  7. using ESolutions.Models;  
  8. namespace ESolutions.Controllers  
  9. {  
  10.     public class EHomeController : Controller  
  11.     {  
  12.         CRUDOprClient objClient = new CRUDOprClient();  
  13.         public ActionResult Index()  
  14.         {  
  15.             //calling the service function for retrieving all the employees data  
  16.             List<Employee> lstEmployees = objClient.GetAllEmployees();  
  17.           Session["eData"] = lstEmployees;//storing the Employee Data to Session Object  
  18.             List<EmployeeViewModel> lstEModel = lstEmployees.Select(x => new EmployeeViewModel  
  19.             {  
  20.                 EmployeeID = x.EmployeeID,  
  21.                 Department = x.Department,  
  22.                 Address = x.Address,  
  23.                 Name = x.Name,  
  24.             }).ToList();  
  25.             return View("Index", lstEModel);  
  26.         }  
  27.     }  
  28. }  

Then right-click on the Index() and click on AddView to create a view for our application data display purposes. When creating the view kindly select a Strongly Type view option and also set the default layout to the _Layout.cshtml and select the Scaffold option to List. The following is the snapshot of that

Note: Before creating the view kindly just build the application so that your models are reflected when you select the strongly typed view when adding the view.

Before creating the view

The following code will be added to your applications Index view:
  1. @model IEnumerable<ESolutions.Models.EmployeeViewModel>  
  2. @{  
  3.     ViewBag.Title = "Index";  
  4.     Layout = "~/Views/Shared/_Layout.cshtml";  
  5. }  
  6. <h2>Index</h2>  
  7. <p>  
  8.     @Html.ActionLink("Create New""Create")  
  9. </p>  
  10. <table>  
  11.     <tr>  
  12.         <th>  
  13.             @Html.DisplayNameFor(model => model.Name)  
  14.         </th>  
  15.         <th>  
  16.             @Html.DisplayNameFor(model => model.Address)  
  17.         </th>  
  18.         <th>  
  19.             @Html.DisplayNameFor(model => model.Department)  
  20.         </th>  
  21.         <th></th>  
  22.     </tr>  
  23. @foreach (var item in Model) {  
  24.     <tr>  
  25.         <td>  
  26.             @Html.DisplayFor(modelItem => item.Name)  
  27.         </td>  
  28.         <td>  
  29.             @Html.DisplayFor(modelItem => item.Address)  
  30.         </td>  
  31.         <td>  
  32.             @Html.DisplayFor(modelItem => item.Department)  
  33.         </td>  
  34.         <td>  
  35.             @Html.ActionLink("Edit""Edit"new { id=item.EmployeeID }) |  
  36.             @Html.ActionLink("Details""Details"new { id=item.EmployeeID }) |  
  37.             @Html.ActionLink("Delete""Delete"new { id=item.EmployeeID })  
  38.         </td>  
  39.     </tr>  
  40. }  
  41. </table>

Notice that for your photo column there is no entry in the view, we need to manually add the entry for that. After adding the entry your view will look like the following:

  1. @model IEnumerable<ESolutions.Models.EmployeeViewModel>  
  2. @{  
  3.     ViewBag.Title = "Index";  
  4.     Layout = "~/Views/Shared/_Layout.cshtml";  
  5. }  
  6. <h2>Index</h2>  
  7. <p>  
  8.     @Html.ActionLink("Create New""Create")  
  9. </p>  
  10. <table>  
  11.     <tr>  
  12.         <th>  
  13.             @Html.DisplayNameFor(model => model.EmployeeID)  
  14.         </th>  
  15.         <th>  
  16.             @Html.DisplayNameFor(model => model.Name)  
  17.         </th>  
  18.         <th>  
  19.             @Html.DisplayNameFor(model => model.Address)  
  20.         </th>  
  21.         <th>  
  22.             @Html.DisplayNameFor(model => model.Department)  
  23.         </th>  
  24.         <th>  
  25.             @Html.DisplayNameFor(model => model.Photo)  
  26.         </th>  
  27.         <th></th>  
  28.     </tr>  
  29.     @foreach (var item in Model)  
  30.     {  
  31.         <tr>  
  32.             <td>  
  33.                 @Html.DisplayFor(modelItem => item.EmployeeID)  
  34.             </td>  
  35.             <td>  
  36.                 @Html.DisplayFor(modelItem => item.Name)  
  37.             </td>  
  38.             <td>  
  39.                 @Html.DisplayFor(modelItem => item.Address)  
  40.             </td>  
  41.             <td>  
  42.                 @Html.DisplayFor(modelItem => item.Department)  
  43.             </td>  
  44.             <td>  
  45.                 <!--Here we added a Url Action to GetImage which will be an action method also for routing we are ing the EmployeeID  
  46.                      inside EHome controller-->  
  47.                 <img width="50" height="50"  src="@Url.Action("GetImage", "EHome", new { item.EmployeeID })" />  
  48.             </td>  
  49.             <td>  
  50.                 @Html.ActionLink("Edit""Edit"new { id = item.EmployeeID }) |  
  51.             @Html.ActionLink("Details""Details"new { id = item.EmployeeID }) |  
  52.             @Html.ActionLink("Delete""Delete"new { id = item.EmployeeID })  
  53.             </td>  
  54.         </tr>  
  55.     }  
  56. </table>

Now it's time to add the GetImage Action Method since that method is used for displaying the image of the employees. Write the following function inside the EHomeController.cs file:

  1. public FileContentResult GetImage(int employeeID)  
  2. {  
  3.     List<Employee> lstData = null;  
  4.     if (Session["eData"] != null)  
  5.     {  
  6.         lstData = (List<Employee>)Session["eData"];  
  7.         Employee objEmployee = lstData.FirstOrDefault(x => x.EmployeeID == employeeID);  
  8.         if (objEmployee != null && objEmployee.Photo != null)  
  9.        {  
  10.            return File(objEmployee.Photo, "image");  
  11.       }  
  12.       else  
  13.       {  
  14.            FileStream fs = new FileStream(Server.MapPath("~/Content/images/blank-image.jpg"), FileMode.Open, FileAccess.Read);  
  15.            byte[] rawByte = new byte[fs.Length];  
  16.            fs.Read(rawByte, 0, Convert.ToInt32(fs.Length));  
  17.            return File(rawByte, "image");  
  18.       }  
  19.   }  
  20.   else  
  21.      eturn null;  
  22. }

You can now test the application by running it. You'll get an error message stating that the resource couldn't be found; this is because of the default Routing for MVC. We need to make a minor change in the RouteConfig.cs file that is inside the App_Start folder of your application.

Here the controller name default is specified as "Home"; we need to make it "EHome", that's it.

  1. routes.MapRoute(  
  2.       name: "Default",  
  3.       url: "{controller}/{action}/{id}",  
  4.      defaults: new { controller = "EHome", action = "Index", id = UrlParameter.Optional }  
  5. );

Also if the image stored inside your database is large then when retrieving the image from the database it may throw an error. Make the following changes in your applications web.config file:

  1. <system.serviceModel>  
  2.     <bindings>  
  3.       <basicHttpBinding>  
  4.         <binding name="BasicHttpBinding_ICRUDOpr" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00"  
  5.                  allowCookies="false" byProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"  
  6.                  maxBufferPoolSize="524288" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" textEncoding="utf-8" transferMode="Buffered"  
  7.                  useDefaultWebProxy="true" messageEncoding="Text">  
  8.           <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647"  
  9.                         maxNameTableCharCount="2147483647"/>  
  10.         </binding>  
  11.       </basicHttpBinding>  
  12.     </bindings>  
  13.     <client>  
  14.       <endpoint address="http://localhost:8733/Design_Time_Addresses/CRUDService/CRUDOpr/"  
  15.         binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ICRUDOpr" behaviorConfiguration="Bhw"  
  16.         contract="EService.ICRUDOpr" name="BasicHttpBinding_ICRUDOpr" />  
  17.     </client>  
  18.     <behaviors>  
  19.       <endpointBehaviors>  
  20.         <behavior name="Bhw">  
  21.           <dataContractSerializer maxItemsInObjectGraph="2147483647"/>  
  22.         </behavior>  
  23.       </endpointBehaviors>  
  24.     </behaviors>  
  25. </system.serviceModel> 

Now run the application.

Note: Before running the application throughout this example ensure your service is running because our database level operations are being done by the Service.

run the application

Notice that there is no image in the database table; there the default image is being displayed.

Now we'll try to create a new Employee for which we've already provided the link on the Index View. Add a new ActionMethod in EHomeController like the following:
  1. public ActionResult Create()  
  2. {  
  3.     return View("Create"new EmployeeViewModel());  
  4. }

Add the view like we did above. But this time select the scaffold option to create it keeping everything the same.

The following are the changes that we need to do inside the Create.cshtml View:

  1. @model ESolutions.Models.EmployeeViewModel  
  2. @{  
  3.     ViewBag.Title = "Create";  
  4.     Layout = "~/Views/Shared/_Layout.cshtml";  
  5. }  
  6. <h2>Create</h2>  
  7. <!--Since we are returning data with image we need to set the enctype attribute to "multipart/form-data" -->  
  8. @using (Html.BeginForm("Create""EHome", FormMethod.Post, new { enctype = "multipart/form-data" }))  
  9. {  
  10.     <!--If you want to show validation summary then make the below validationsummary value to false default true. Also while displaying the  
  11.         validation error if you want heading for the validation summary you can provide it by ing the second parameter -->  
  12.     @Html.ValidationSummary(false"Errors on the Page")  
  13.     <fieldset>  
  14.         <legend>Add Employee</legend>  
  15.         <div class="editor-label">  
  16.             @Html.HiddenFor(model => model.EmployeeID)  
  17.         </div>  
  18.         <div class="editor-label">  
  19.             @Html.LabelFor(model => model.Name)  
  20.         </div>  
  21.         <div class="editor-field">  
  22.             @Html.EditorFor(model => model.Name)  
  23.             @Html.ValidationMessageFor(model => model.Name, "*")  
  24.         </div>  
  25.         <div class="editor-label">  
  26.             @Html.LabelFor(model => model.Address)  
  27.         </div>  
  28.         <div class="editor-field">  
  29.             @Html.EditorFor(model => model.Address)  
  30.             @Html.ValidationMessageFor(model => model.Address, "*")  
  31.         </div>  
  32.         <div class="editor-label">  
  33.             @Html.LabelFor(model => model.Department)  
  34.         </div>  
  35.         <div class="editor-field">  
  36.             @Html.EditorFor(model => model.Department)  
  37.             @Html.ValidationMessageFor(model => model.Department, "*")  
  38.         </div>  
  39.         <div class="editor-label">  
  40.             Photo  
  41.         </div>  
  42.         <div class="editor-field">  
  43.             @if (Model.Photo == null)  
  44.             {  
  45.                 @:None<!--This is used for writing on browse same as <%=%> in asp.net-->  
  46.             }  
  47.             else  
  48.             {  
  49.                 <img width="70" height="70" style="border:2px solid black;" src="@Url.Action("GetImage", "EHome", new { Model.EmployeeID })" />  
  50.             }  
  51.             <div>  
  52.                 Upload new image:  
  53.             <input type="file" name="Image" />  
  54.             </div>  
  55. @Html.ValidationMessageFor(model => model.Photo)   
  56. </div>  
  57.         <p>  
  58.             <input type="submit" value="Create" />  
  59.         </p>  
  60.     </fieldset>  
  61. }  
  62. <div>  
  63.     @Html.ActionLink("Back to List""Index")  
  64. </div>  
  65. @section Scripts {  
  66.     @Scripts.Render("~/bundles/jqueryval")  
  67. }
In the CreateNew.cshtml page there is one button on whose click the data that the user enter should be saved. For this I've added a new action method inside EHomecontroller with the name Create() only but decorated with the [HttpPost] attribute. The following is the code for that.
  1. [HttpPost]//This denotes that this action method will be called only for post requests.  
  2. public ActionResult Create(EmployeeViewModel objEmployee, HttpPostedFileBase image)  
  3. {  
  4.     if (ModelState.IsValid)  
  5.     {  
  6.         byte[] rawBytes = null;  
  7.         if (image != null)  
  8.         {  
  9.             rawBytes = new byte[image.ContentLength];  
  10.             image.InputStream.Read(rawBytes, 0, image.ContentLength);  
  11.         }  
  12.         else  
  13.         {  
  14.             //if image is null then set the default image  
  15.             FileStream fs = new FileStream(Server.MapPath("~/Content/images/blank-image.jpg"), FileMode.Open, FileAccess.Read);  
  16.             rawBytes = new byte[fs.Length];  
  17.             fs.Read(rawBytes, 0, Convert.ToInt32(fs.Length));  
  18.         }  
  19.         List<Employee> lstEmployee = new List<Employee>();  
  20.         lstEmployee.Add(new Employee()  
  21.         {  
  22.             EmployeeID = objEmployee.EmployeeID,  
  23.             Address = objEmployee.Address,  
  24.             Department = objEmployee.Department,  
  25.             Name = objEmployee.Name,  
  26.             Photo = rawBytes  
  27.         });  
  28.         int rows = objClient.AddEmployee(lstEmployee);  
  29.         if (rows > 0)  
  30.             return RedirectToAction("Index");// if the row is added then redirect to action index  
  31.         else  
  32.             return View("Create");  
  33.     }  
  34.     return View("Create");  
  35. } 

Now run the solution and click on the "Create New" link. The following is the snapshot for that.

If you don't provide the full details then the validation errors will be fired as in the following:

validation errors

Fill in the details and once you click on the Create Button a new employee will be added to your application.
 
new employee added

Similarly you can do that for an edit. For the full code download the article.


Similar Articles