How to Create Custom Service in AngularJS for CRUD Operations on SharePoint List

Ahamed Fazil Buhari
 
Senior Developer
October 11, 2016
 
Rate this article
 
Views
11766

In this article, we’ll look into the advantages and how to implement Custom Services in Angular. Before going further, please refer my previous articles on $http service in Angular. Here, I’ve implemented CRUD operations on SharePoint List using Angular HTTP service and having that in my own Custom service.

‘Why would we need to write a custom service?’ the answer is simple, Services are useful in various scenarios,

· Packaging Reusable Logic – we can have some logic (an algorithm or some piece of code that we need in several different controllers) in a container and we can use that in different places, it would avoid duplicating of code.

· Shared Data – If we want to share data between the controllers on different views, a service will be a great place to store data. Because Angular only instantiate a single instance of each service in an application.

· Complexity Is Reduced – Sometimes a controller would be too difficult to manage if we have so much code in it. So in that situation we can simplify the code and separate the responsibilities and give some burden to the service.

· Clean Maintainable Code – Organizing your code into services leads to cleaner, better defined components which means we have an application with more maintainable code.

In the following example, we will have SharePoint List Item CRUD operation in an Angular Custom Service named as, MyCustomService.js

 (function () { //IIFE 
 
     //RequestHeader for get,post,update,delete
     var requestHeader = {
         getHeader: {
             'headers': {
                 'accept': 'application/json;odata=verbose'
             }
         },
         postHeader: {
             'headers': {
                 "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                 'content-type': 'application/json;odata=verbose',
                 'accept': 'application/json;odata=verbose'
             }
         },
         deleteHeader: {
             'headers': {
                 "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                 'content-type': 'application/json;odata=verbose',
                 "IF-MATCH": "*"
             }
         },
         updateHeader: {
             'headers': {
                 "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                 'content-type': 'application/json;odata=verbose',
                 'accept': 'application/json;odata=verbose',
                 "IF-MATCH": "*",
                 "X-HTTP-Method": "MERGE"
             }
         }
     };
 
     //A service can have dependency on another service – Here we’ve used $http service
     var CRUD_SP = function ($http) {
 	 //Defining Function with parameter, 
         //same number of parameter we use when we invoke this function	
         var getListData = function (urlValue) {
             return $http.get(urlValue, requestHeader.getHeader)
 						.then(function (response) {
 						    return response.data.d.results;
 						});
         };
 
         var setListData = function (urlValue, data) {
             return $http.post(urlValue, data, requestHeader.postHeader)
 						.then(function (response) {
 						    return 'Created from Custom Service...';
 						});
         };
 
         var deleteListData = function (urlValue) {
             return $http.delete(urlValue, requestHeader.deleteHeader)
 						.then(function (response) {
 						    return 'Deleted from Custom Service...';
 						});
         };
 
         var updateListData = function (urlValue, data) {
             return $http.post(urlValue, data, requestHeader.updateHeader)
 						.then(function (response) {
 						    return 'Updated from Custom Service...';
 						});
         };
 
         //When someone invokes this CRUD_SP function
         //then it'll return an Object that is of CRUD_SP
         return {
             //Pick up the Public API
             //name: function_name to call
             getListData: getListData,
             setListData: setListData,
             updateListData: updateListData,
             deleteListData: deleteListData
         };
     };
 
     //Creating the reference to "myapp" which we defined in MyAngular.js and 
     //No 2nd parameter, bcz I'm not trying to create a Module
     //rest of the code goes above this module.
     var module = angular.module("myapp");
 
     //Registering our service, so that Angular will use this
     //There are various ways to Register the service
     //This is simple and straightforward way,
     //Make use of method called 'factory('Name of the service', function name that returs an object)'
     module.factory('CRUD_SP', CRUD_SP);
 
 }());
 

The above js file will be used as a Custom Service. The code written in our main JS file has been reduced and we can use this custom service in other places in our application. The main JS file code has been given below,

 (function () { //IIFE 
     //angular.module(,) in this second parameter is an array, 
     //earlier we had empty bcz we don't have any explicit dependencies,
     //
     var app = angular.module("myapp", []);
 
     //Add our new service in the controller parameter
     var MyController = function ($scope, CRUD_SP) {
 
         var urlVal = {
             url: _spPageContextInfo.webAbsoluteUrl + "/_api" + "/web/lists/GetByTitle('Phone')/Items"
         };
         //Function to call for Successful GET
         var onSuccessGet = function (data) {
             $scope.people = data;
             console.log(data);
         };
         //Function to call for Successful post,update,delete
         var onSuccess = function (data) {
             $scope.phonename = '';
             $scope.pplusing = '';
             $scope.newphonename = '';
             $scope.newpplusing = '';
             $scope.itemID = '';
             $scope.error = '';
             $scope.getItem();
             console.log(data);
         };
 
         var onError = function (reason) {
             $scope.error = "something went wrong";
         };
 
         $scope.getItem = function () {
             var geturlVal = urlVal.url + "/?$select=*";
             //using CRUD_SP custom service and calling function defined inside it
             CRUD_SP.getListData(geturlVal)
 				   .then(onSuccessGet, onError);
         }
 
         $scope.saveItem = function () {
             var createURL = urlVal.url;
             var data = {
                 //To Get __metadata->'type' value for the list, go to
                 //https://<site>/_api/web/lists/getbytitle('<List Name>')?$select=ListItemEntityTypeFullName
                 //from the xml, get the value inside <d:ListItemEntityTypeFullName> element
                 __metadata: { 'type': 'SP.Data.TestingListItem' },
                 Title: $scope.phonename,
                 People_x0020_using: $scope.pplusing
             };
 
             CRUD_SP.setListData(createURL, data)
                    .then(onSuccess, onError);
         }
 
         $scope.deleteItem = function () {
             var deleteURL = urlVal.url + '(' + $scope.itemID + ')';
             CRUD_SP.deleteListData(deleteURL)
 	    		.then(onSuccess, onError);
         }
 
         $scope.updateItem = function () {
             var updateURL = urlVal.url + '(' + $scope.itemID + ')';
             var updatedata = {
                 __metadata: { 'type': 'SP.Data.TestingListItem' },
                 Title: $scope.newphonename,
                 People_x0020_using: $scope.newpplusing
             };
 
             CRUD_SP.updateListData(updateURL, updatedata)
 	    		.then(onSuccess, onError);
         }
     };
 
     app.controller("MyController", MyController);
 }());
 
 

In the aspx page, we’re having buttons and text fields to update, delete and insert list items and HTML table to show the data.

 <script src="../SiteAssets/JS/Form JS/jquery-1.10.2.js"></script>
 <script src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
 
 <script src="../SiteAssets/JS/Form JS/MyAngular.js"></script>
 <!-- Make sure your service is defined after Main JS i.e MyAngular.js,
 bcz module has been defind in MyAngular.js!-->
 <script src="../SiteAssets/JS/Form JS/MyCustomService.js"></script>
 
 
 <div id="appDiv" ng-app="myapp">
     <div id="controllerDiv" ng-controller="MyController">
         <label ng-show="error" class="ng-hide">Error : {{error}}</label>
         <h2>Insert into List</h2>
         Phone Name : <input type="text" ng-model="phonename" />
         No. of People Usng : <input type="number" ng-model="pplusing" />
         <button type="button" ng-click="saveItem()">Save</button>
 
         <h2>Delete or Update List Item</h2>
         Enter Item ID : <input type="text" ng-model="itemID" />
         New Phone Name : <input type="text" ng-model="newphonename" />
         New No. of People Usng : <input type="number" ng-model="newpplusing" />
         <button type="button" ng-click="deleteItem()">Delete</button>
         <button type="button" ng-click="updateItem()">Update</button>
 
         <button type="button" ng-click="getItem()">Get Items</button>
         <div ng-show="people" class="ng-hide">
             <table id="userDetails" border="1px solid">
                 <thead>
                     <tr>
                         <th>Item ID</th>
                         <th>Phone Title</th>
                         <th>No. of ppl using</th>
                     </tr>
                 </thead>
                 <tbody>
                     <tr ng-repeat="ppl in people">
                         <td>{{ppl.ID}}</td>
                         <td>{{ppl.Title}}</td>
                         <td>{{ppl.People_x0020_using | number}}</td>
                     </tr>
                 </tbody>
             </table>
         </div>
     </div>
 </div>
 
 

clip_image002

Happy Coding

Ahamed

Author Info

Ahamed Fazil Buhari
 
Senior Developer
 
Rate this article
 
Ahamed is a Senior Developer and he has very good experience in the field of Microsoft Technologies, especially SharePoint, Azure, M365, SPFx, .NET and client side scripting - JavaScript, TypeScript, ...read more
 

CRUD Operation on various field Types in SharePoint List using SPServices – SharePoint 2013

Ahamed Fazil Buhari
 
Senior Developer
June 7, 2016
 
Rate this article
 
Views
10701

In this article, let us see some of the basic operations on various field types in SharePoint List using SPServices.

Before dealing with SPServices in SharePoint 2013, Let us go through the definitions of SPServices from MSDN

– SPServices is a jQuery library which abstracts SharePoint’s Web Services and makes them easier to use.

– It also includes functions which use the various Web Service operations to provide more useful (and cool) capabilities.

– It works entirely client side and requires no server install.

Here, you can find Create operation on different SharePoint field types namely –

· Single line of text

· Multiple line of text

· Date

· People picker

· Lookup (Single & Multiple)

· Choice.

In this article, let us have a look on the Item Creation: The rest of the operations, I am leaving to the readers.

 var valuePair = []; //Array variable to hold all the Field_Internal_Name and its value.
 valuePair.push(["Column_Text1_InternalName", colText1]); 
 //Single line of text field
 valuePair.push(["Lookup_single_InternalName", Lookup_FieldID +';#'+LookupText]); 
 //Lookup field
 // Lookup_FieldID -> ID of lookup list item which has been selected
 // LookupText -> Text of lookup list item which has been selected
 var isoDate = {extracted_Date}.toISOString(); //Date Field
 //convert the date value into ISOString() format which is understandable by SharePoint
 valuePair.push(["Date_InternalName", isoDate]);
 var peoplePicker = $("[id$='PeoplePicker_ID']>span>div").attr("key"); 
 // People picker field
 var userID = null;
 $().SPServices({
     operation: "GetUserInfo",
     async: false,
     userLoginName: peoplePicker,
     completefunc: function (xData, Status) {
         $(xData.responseXML).find("User").each(function() {
             userID = $(this).attr("ID");
         });
     }
 });
 valuePair.push(["Peoplepicker_InternalName, userID]);
 //SPServices accepts User ID for people picker field while creation of new item
 valuePair.push(["Lookup_multiple_InternalName", Lookup_FieldID1 +';#'+LookupText1 + ';#' + Lookup_FieldID2 + ';#' + LookupText1 ]);
 // LookupText -> ID of lookup list item which has been selected
 // LookupText -> Text of lookup list item which has been selected
 //To save multiple lookup field -> append ‘;#’ after every ID, text and next value
 
 //SPServices to Create an Item.
 $().SPServices({
     operation: "UpdateListItems",
     async: false,
     listName: "Name of the list",
     batchCmd: "New",
     valuepairs: valuePair,
     completefunc: function (xData, Status) {
         if (Status != "success" || $(xData.responseXML).find('ErrorCode').text() !== "0x00000000") {
             alert("Error in saving the item.");
         }
         else {
             if (Status == "success") {
                 alert("Item created successfully...");
             }
         }
     }
 });	
 

Though this is very straight forward, this will save a lot of development effort for sure.

Click HERE to download the SPService JQuery Plugin.

Happy Coding,

Ahamed Buhari

Author Info

Ahamed Fazil Buhari
 
Senior Developer
 
Rate this article
 
Ahamed is a Senior Developer and he has very good experience in the field of Microsoft Technologies, especially SharePoint, Azure, M365, SPFx, .NET and client side scripting - JavaScript, TypeScript, ...read more
 

Entity Framework Database first approach to Read/Insert/Update/Delete the database data in Asp.Net MVC & C#

Tarun Kumar Chatterjee
 
Net – Technology Specialist
May 16, 2016
 
Rate this article
 
Views
8833

We use Entity Framework designer which is in built feature of Visual Studio for automatically generate a data model with classes and properties of existing database tables and columns. The information about your database structure (store schema), your data model (conceptual model) and the mapping between them is stored in XML in an .edmx file. Entity Framework designer provides a graphical interface for display and edit the .edmx file.

Let’s first create a database with tables & procedures. Execute the below script to create tables & procedures within the MyEmployeeDB database

 USE [MyEmployeeDB]
 GO
 /****** Object:  StoredProcedure [dbo].[GetEmployeeByEmployeeId]    Script Date: 1/28/2016 5:17:52 PM ******/
 SET ANSI_NULLS ON
 GO
 SET QUOTED_IDENTIFIER ON
 GO
 CREATE PROCEDURE [dbo].[GetEmployeeByEmployeeId]
     -- Add the parameters for the stored procedure here
     @EmployeeId int = null
 AS
 BEGIN
     -- SET NOCOUNT ON added to prevent extra result sets from
     -- interfering with SELECT statements.
     SET NOCOUNT ON;
 
     -- Insert statements for procedure here
 SELECT [Id]
       ,[Name]
       ,[Address]
       ,[DOB]
   FROM [dbo].[Employees]
 WHERE [Id] = @EmployeeId
 END
 GO
 /****** Object:  StoredProcedure [dbo].[sp_DeleteEmployee]    Script Date: 1/28/2016 5:17:52 PM ******/
 SET ANSI_NULLS ON
 GO
 SET QUOTED_IDENTIFIER ON
 GO
 CREATE PROCEDURE [dbo].[sp_DeleteEmployee]
     -- Add the parameters for the stored procedure here
     @Id int
 AS
 BEGIN
     -- SET NOCOUNT ON added to prevent extra result sets from
     -- interfering with SELECT statements.
     SET NOCOUNT ON;
 
     DELETE FROM [dbo].[Employees]
     WHERE [Id] = @Id;
 
 END
 GO
 /****** Object:  StoredProcedure [dbo].[sp_InsertEmployee]    Script Date: 1/28/2016 5:17:52 PM ******/
 SET ANSI_NULLS ON
 GO
 SET QUOTED_IDENTIFIER ON
 GO
 CREATE PROCEDURE [dbo].[sp_InsertEmployee]
     -- Add the parameters for the stored procedure here
     @Name NVARCHAR(MAX),
 	@Address NVARCHAR(MAX),
     @DOB NVARCHAR(MAX)
 AS
 BEGIN
     -- SET NOCOUNT ON added to prevent extra result sets from
     -- interfering with SELECT statements.
     SET NOCOUNT ON;
 
         INSERT INTO [dbo].[Employees]([Name],[Address],[DOB])
         VALUES(@Name, @Address,@DOB)
 
     SELECT SCOPE_IDENTITY() AS Id
 
 END
 GO
 /****** Object:  StoredProcedure [dbo].[sp_UpdateEmployee]    Script Date: 1/28/2016 5:17:52 PM ******/
 SET ANSI_NULLS ON
 GO
 SET QUOTED_IDENTIFIER ON
 GO
 CREATE PROCEDURE [dbo].[sp_UpdateEmployee]
     -- Add the parameters for the stored procedure here
     @Id int,
     @Name NVARCHAR(MAX),
 	@Address NVARCHAR(MAX),
     @DOB NVARCHAR(MAX)
 AS
 BEGIN
     -- SET NOCOUNT ON added to prevent extra result sets from
     -- interfering with SELECT statements.
     SET NOCOUNT ON;
 
     UPDATE [dbo].[Employees]
     SET [Name] = @Name,[Address] = @Address, [DOB] = @DOB
     WHERE [Id] = @Id;
 
 END
 GO
 /****** Object:  Table [dbo].[Employees]    Script Date: 1/28/2016 5:17:52 PM ******/
 SET ANSI_NULLS ON
 GO
 SET QUOTED_IDENTIFIER ON
 GO
 CREATE TABLE [dbo].[Employees](
 	[Id] [int] IDENTITY(1,1) NOT NULL,
 	[Name] [nvarchar](max) NOT NULL,
 	[Address] [nvarchar](max) NOT NULL,
 	[DOB] [nvarchar](max) NOT NULL,
  CONSTRAINT [PK_Employees] PRIMARY KEY CLUSTERED 
 (
 	[Id] ASC
 )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
 ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
 
 GO
 SET IDENTITY_INSERT [dbo].[Employees] ON 
 
 INSERT [dbo].[Employees] ([Id], [Name], [Address], [DOB]) VALUES (1, N'Tarun1', N'Kolkata1', N'2016-01-01')
 INSERT [dbo].[Employees] ([Id], [Name], [Address], [DOB]) VALUES (3, N'Tarun3', N'Kolkata3', N'2016-01-01')
 INSERT [dbo].[Employees] ([Id], [Name], [Address], [DOB]) VALUES (4, N'Tarun4', N'Kolkata4', N'2016-01-03')
 INSERT [dbo].[Employees] ([Id], [Name], [Address], [DOB]) VALUES (1002, N'Tarun8', N'Kolkata8', N'2016-01-01')
 SET IDENTITY_INSERT [dbo].[Employees] OFF
 

Now, we will be creating the models in Visual studio from the database

Open Visual Studio 2013 and click on New Project.

Select the MVC Project Template and click on OK.

In this section, we will add the ADO.NET Entity Data Model to the application. We will create the generate from database model in here. Use the following procedure.

In the Solution Explorer, right-click on the Models folder and click on ADO.NET Entity Data Model.

clip_image002

Click on Next & then new connection

Select the server name & database name where we have created all the tables & procedures.

clip_image004

Click on Ok & then Next

Select the tables and procedures you wanted to include into the model

 

clip_image006

Click on Finish

It will take some times to create the entity model under the solution

Below is the code generated automatically in EmployeeModel.Context.cs

 
 //------------------------------------------------------------------------------
 // <auto-generated>
 //    This code was generated from a template.
 //
 //    Manual changes to this file may cause unexpected behavior in your application.
 //    Manual changes to this file will be overwritten if the code is regenerated.
 // </auto-generated>
 //------------------------------------------------------------------------------
 
 namespace EntityFrameworkDemo.Models
 {
     using System;
     using System.Data.Entity;
     using System.Data.Entity.Infrastructure;
     using System.Data.Entity.Core.Objects;
     using System.Linq;
     
     public partial class MyEmployeeDBEntities : DbContext
     {
         public MyEmployeeDBEntities()
             : base("name=MyEmployeeDBEntities")
         {
         }
     
         protected override void OnModelCreating(DbModelBuilder modelBuilder)
         {
             throw new UnintentionalCodeFirstException();
         }
     
         public DbSet<Employee> Employees { get; set; }
     
         public virtual ObjectResult<GetEmployeeByEmployeeId_Result> GetEmployeeByEmployeeId(Nullable<int> employeeId)
         {
             var employeeIdParameter = employeeId.HasValue ?
                 new ObjectParameter("EmployeeId", employeeId) :
                 new ObjectParameter("EmployeeId", typeof(int));
     
             return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<GetEmployeeByEmployeeId_Result>("GetEmployeeByEmployeeId", employeeIdParameter);
         }
     
         public virtual int sp_DeleteEmployee(Nullable<int> id)
         {
             var idParameter = id.HasValue ?
                 new ObjectParameter("Id", id) :
                 new ObjectParameter("Id", typeof(int));
     
             return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("sp_DeleteEmployee", idParameter);
         }
     
         public virtual ObjectResult<Nullable<decimal>> sp_InsertEmployee(string name, string address, string dOB)
         {
             var nameParameter = name != null ?
                 new ObjectParameter("Name", name) :
                 new ObjectParameter("Name", typeof(string));
     
             var addressParameter = address != null ?
                 new ObjectParameter("Address", address) :
                 new ObjectParameter("Address", typeof(string));
     
             var dOBParameter = dOB != null ?
                 new ObjectParameter("DOB", dOB) :
                 new ObjectParameter("DOB", typeof(string));
     
             return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<Nullable<decimal>>("sp_InsertEmployee", nameParameter, addressParameter, dOBParameter);
         }
     
         public virtual int sp_UpdateEmployee(Nullable<int> id, string name, string address, string dOB)
         {
             var idParameter = id.HasValue ?
                 new ObjectParameter("Id", id) :
                 new ObjectParameter("Id", typeof(int));
     
             var nameParameter = name != null ?
                 new ObjectParameter("Name", name) :
                 new ObjectParameter("Name", typeof(string));
     
             var addressParameter = address != null ?
                 new ObjectParameter("Address", address) :
                 new ObjectParameter("Address", typeof(string));
     
             var dOBParameter = dOB != null ?
                 new ObjectParameter("DOB", dOB) :
                 new ObjectParameter("DOB", typeof(string));
     
             return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("sp_UpdateEmployee", idParameter, nameParameter, addressParameter, dOBParameter);
         }
     }
 }
 
 Now, within the Models folder we will be creating a custom business class named as EmployeeBusinessLayer
 public class EmployeeBusinessLayer
     {
         int num = 0;
         public int EditEmployee(Employee emp)
         {
             MyEmployeeDBEntities empDal = new MyEmployeeDBEntities();
             num = empDal.sp_UpdateEmployee(emp.Id, emp.Name, emp.Address, emp.DOB);
             return num;
         }
         public ObjectResult<Nullable<decimal>> InsertEmployee(Employee emp)
         {
             ObjectResult<Nullable<decimal>> objResult = null;
             MyEmployeeDBEntities empDal = new MyEmployeeDBEntities();
             objResult = empDal.sp_InsertEmployee(emp.Name, emp.Address, emp.DOB);
             return objResult;
         }
         public int DeleteEmployee(int empID)
         {
             MyEmployeeDBEntities empDal = new MyEmployeeDBEntities();
             num = empDal.sp_DeleteEmployee(empID);
             return num;
         }
         public List<Employee> GetEmployee()
         {
             MyEmployeeDBEntities empDal = new MyEmployeeDBEntities();
             return empDal.Employees.ToList();            
         }
         public ObjectResult<GetEmployeeByEmployeeId_Result> GetEmployeeByEmployeeID(int empID)
         {
             MyEmployeeDBEntities empDal = new MyEmployeeDBEntities();
             return empDal.GetEmployeeByEmployeeId(empID);
         }
     }
 Next we will be modifying the Controller 
 public class HomeController : Controller
     {
         EmployeeBusinessLayer db = new EmployeeBusinessLayer();
         
         public ActionResult Index()
         {
             return View(db.GetEmployee());
         }
 
         public ActionResult Create()
         {
             return View();
         }        
 
         [HttpPost]
         public ActionResult Create(Employee emp)
         {
             try
             {
                 db.InsertEmployee(emp);                
                 return RedirectToAction("Index");
             }
             catch
             {
                 return View();
             }
         }
 
         public ActionResult Edit(int id)
         {
             Employee emp = new Employee();
             List<GetEmployeeByEmployeeId_Result> result = db.GetEmployeeByEmployeeID(id).ToList();
             emp.Id = result[0].Id;
             emp.Name = result[0].Name;
             emp.Address = result[0].Address;
             emp.DOB = result[0].DOB;
             return View(emp);
         }
 
 
         [HttpPost]
         public ActionResult Edit(int id, Employee emp)
         {
             try
             {                
                 db.EditEmployee(emp);
                 return RedirectToAction("Index");
             }
             catch
             {
                 return View();
             }
         }
 
         public ActionResult Delete(int id)
         {
             Employee emp = new Employee();
             List<GetEmployeeByEmployeeId_Result> result = db.GetEmployeeByEmployeeID(id).ToList();
             emp.Id = result[0].Id;
             emp.Name = result[0].Name;
             emp.Address = result[0].Address;
             emp.DOB = result[0].DOB;
             return View(emp);
         }
 
 
         [HttpPost]
         public ActionResult Delete(int id, Employee emp)
         {
             try
             {                
                 db.DeleteEmployee(id);                
                 return RedirectToAction("Index");
             }
             catch
             {
                 return View();
             }
         }
     }
 Here are my Views code.
 Index View code: 
 @model IEnumerable<EntityFrameworkDemo.Models.Employee>
 @{
     ViewBag.Title = "Index";
 }
 
 <h2>Index</h2>
 <p>
     @Html.ActionLink("Create New", "Create")
 </p>
 <table border="1" width="50%">
     <tr>
         <th width="40%"></th>
         <th width="20%">
             Name
         </th>
         <th width="20%">
             Address
         </th>
         <th width="20%">
             DOB
         </th>
     </tr>
 
 @foreach (var item in Model) {
     <tr>
         <td>
             @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
             @Html.ActionLink("Delete", "Delete", new { id=item.Id })
         </td>
         <td>
             @item.Name
         </td>
         <td>
             @item.Address
         </td>
         <td>
             @item.DOB
         </td>
     </tr>
 }
 
 </table>
 
 
 Edit View code:
 @model EntityFrameworkDemo.Models.Employee
 
 @{
     ViewBag.Title = "Edit";
 }
 
 <h2>Edit</h2>
 
 <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
 <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
 
 @using (Html.BeginForm()) {
     @Html.ValidationSummary(true)
     <fieldset>
         <legend>Employee</legend>
 
         @Html.HiddenFor(model => model.Id)
 
         <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.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.DOB)
         </div>
         <div class="editor-field">
             @Html.EditorFor(model => model.DOB)
             @Html.ValidationMessageFor(model => model.DOB)
         </div>
 
         <p>
             <input type="submit" value="Save" />
         </p>
     </fieldset>
 }
 
 <div>
     @Html.ActionLink("Back to List", "Index")
 </div>
 
 Delete View code: 
 @model EntityFrameworkDemo.Models.Employee
 
 @{
     ViewBag.Title = "Delete";
 }
 
 <h2>Delete</h2>
 <h3>Are you sure you want to delete this?</h3>
 <fieldset>
     <legend>Employee</legend>
 
     <div class="display-label">Name</div>
     <div class="display-field">@Model.Name</div>
 
     <div class="display-label">Address</div>
     <div class="display-field">@Model.Address</div>
 </fieldset>
 @using (Html.BeginForm()) {
     <p>
         <input type="submit" value="Delete" /> |
         @Html.ActionLink("Back to List", "Index")
     </p>
 }
 
 
 Create View code:
 @model EntityFrameworkDemo.Models.Employee
 
 @{
     ViewBag.Title = "Create";
 }
 
 
 <h2>Create</h2>
 <script src="~/Scripts/jquery-1.4.1.min.js"></script>
 <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
 <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
 
 @using (Html.BeginForm()) {
     @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.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.DOB)
         </div>
         <div class="editor-field">
             @Html.EditorFor(model => model.DOB)
             @Html.ValidationMessageFor(model => model.DOB)
         </div>
 
         <p>
             <input type="submit" value="Create" />
         </p>
     </fieldset>
 }
 
 <div>
     @Html.ActionLink("Back to List", "Index")
 </div>
 

Build & run the solution, the output will be looking like:

clip_image008

Edit View output:

clip_image010

Delete View output:

clip_image012

Create New View output:

clip_image014

Happy Coding

Tarun Kumar Chatterjee

Category : .Net, SQL

Author Info

Tarun Kumar Chatterjee
 
Net – Technology Specialist
 
Rate this article
 
Tarun has been working in IT Industry for over 12+ years. He holds a B-tech degree. He is passionate about learning and sharing the tricks and tips in Azure, .Net ...read more
 

Entity Framework Model first approach to Read/Insert/Update/Delete database data in Asp.Net MVC & C#

Tarun Kumar Chatterjee
 
Net – Technology Specialist
May 14, 2016
 
Rate this article
 
Views
11223

Open Visual Studio 2013 and click on New Project.

Select the MVC Project Template and click on OK.

In this section, we will add the ADO.NET Entity Data Model to the application. We will create the empty model in here. Use the following procedure.

In the Solution Explorer, right-click on the Models folder and click on ADO.NET Entity Data Model.

clip_image002

Specify the model name as EmployeeModel.

In the next Entity Data Model Wizard, select the Empty Model and click on "Finish".

clip_image004

Now you can see the Entity Data Model Designer.

Within the designer Right click — > Add new — > Entity

In the next Add Entity wizard, specify the entity name.

clip_image006

Now you can see that the entity is created. So, it is time to add a scalar property to the entity. Right-click on the entity and go to add new scalar property.

clip_image008

Now we have generated an entity model. You can also create more entity models in the Data Model Designer. We will now generate the database from the model. Use the following procedure.

clip_image010

Now in the Generate Database Wizard, click on New Connection to connect with the database.

 

clip_image012

In the next Connection Properties wizard, specify the server name and the specify the database name.

clip_image014

 

The database summary and script is generated and click on Finish.

clip_image016

It will generate the database & create EmployeeModel.edmx.sql with the following script

— ————————————————–

— Entity Designer DDL Script for SQL Server 2005, 2008, and Azure

— ————————————————–

— Date Created: 01/27/2016 18:41:19

— Generated from EDMX file: D:\Project\EntityFrameworkDemo\EntityFrameworkDemo\Models\EmployeeModel.edmx

— ————————————————–

SET QUOTED_IDENTIFIER OFF;

GO

USE [MyEmployeeDB];

GO

IF SCHEMA_ID(N’dbo’) IS NULL EXECUTE(N’CREATE SCHEMA [dbo]’);

GO

— ————————————————–

— Dropping existing FOREIGN KEY constraints

— ————————————————–

— ————————————————–

— Dropping existing tables

— ————————————————–

IF OBJECT_ID(N'[dbo].[Employees]’, ‘U’) IS NOT NULL

DROP TABLE [dbo].[Employees];

GO

— ————————————————–

— Creating all tables

— ————————————————–

— Creating table ‘Employees’

CREATE TABLE [dbo].[Employees] (

[Id] int IDENTITY(1,1) NOT NULL,

[Name] nvarchar(max) NOT NULL,

[Address] nvarchar(max) NOT NULL,

[DOB] nvarchar(max) NOT NULL

);

GO

— ————————————————–

— Creating all PRIMARY KEY constraints

— ————————————————–

— Creating primary key on [Id] in table ‘Employees’

ALTER TABLE [dbo].[Employees]

ADD CONSTRAINT [PK_Employees]

PRIMARY KEY CLUSTERED ([Id] ASC);

GO

— ————————————————–

— Creating all FOREIGN KEY constraints

— ————————————————–

— ————————————————–

— Script has ended

— ————————————————–

 

Now right-click on the script and click on Execute or directly we can go to database & execute the script.

The EmployeeModel.Context file generated from the first template contains the EmployeeModelContainer class shown here:

 public partial class EmployeeModelContainer : DbContext
     {
         public EmployeeModelContainer()
             : base("name=EmployeeModelContainer")
         {
         }
     
         protected override void OnModelCreating(DbModelBuilder modelBuilder)
         {
             throw new UnintentionalCodeFirstException();
         }
     
         public DbSet<Employee> Employees { get; set; }
     }
 

The Employee class is generated in the models folder. Edit the code with the following highlighted code. I have added the Data Annotation in which I am changing the display name of the property, date property initialized & validation attribute.

 public partial class Employee
     {
         public int Id { get; set; }
         [Required(ErrorMessage="Need to provide name")]
         public string Name { get; set; }
         public string Address { get; set; }
  [Display(Name = "DateOfBirth")]
         [DataType(DataType.Date)]
         public string DOB { get; set; 
       }
     }
 

In the code above, I’ve added the Data Annotation in which I am changing the display name of the property and date property initialized.

To enable the validation need to run the following command from package manager console

PM > Install-Package jQuery.Validation.Unobtrusive

Now we will be adding the Controller & Views to perform the CURD operations

Here is my Controller code:

 public class HomeController : Controller
     {
         EmployeeModelContainer db = new EmployeeModelContainer();
         
         public ActionResult Index()
         {
             return View(db.Employees);
         }
 
         public ActionResult Details(int id)
         {
             return View();
         }
 
         
         public ActionResult Create()
         {
             return View();
         }
 
         
         [HttpPost]
         public ActionResult Create(Employee emp)
         {
             try
             {
                 // TODO: Add insert logic here
                 db.Employees.Add(emp);
                 db.SaveChanges();
                 return RedirectToAction("Index");
             }
             catch
             {
                 return View();
             }
         }
 
         
         public ActionResult Edit(int id)
         {
             return View(db.Employees.Find(id));
         }
 
         [HttpPost]
         public ActionResult Edit(int id, Employee emp)
         {
             try
             {
                 // TODO: Add update logic here
                 db.Entry(emp).State = EntityState.Modified;
                 db.SaveChanges();
                 return RedirectToAction("Index");
             }
             catch
             {
                 return View();
             }
         }
 
         public ActionResult Delete(int id)
         {
             return View(db.Employees.Find(id));
         }
 
         [HttpPost]
         public ActionResult Delete(int id, Employee emp)
         {
             try
             {
                 // TODO: Add delete logic here
                 db.Entry(emp).State = EntityState.Deleted;
                 db.SaveChanges();
 
 
                 return RedirectToAction("Index");
             }
             catch
             {
                 return View();
             }
         }
     }
 

Index view code:

 @model IEnumerable<EntityFrameworkDemo.Models.Employee>
 @{
     ViewBag.Title = "Index";
 }
 
 <h2>Index</h2>
 <p>
     @Html.ActionLink("Create New", "Create")
 </p>
 <table border="1" width="50%">
     <tr>
         <th width="40%"></th>
         <th width="20%">
             Name
         </th>
         <th width="20%">
             Address
         </th>
         <th width="20%">
             DOB
         </th>
     </tr>
 
 @foreach (var item in Model) {
     <tr>
         <td>
             @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
             @Html.ActionLink("Delete", "Delete", new { id=item.Id })
         </td>
         <td>
             @item.Name
         </td>
         <td>
             @item.Address
         </td>
         <td>
             @item.DOB
         </td>
     </tr>
 }
 
 </table>
 
 
 Edit view code:
 @model EntityFrameworkDemo.Models.Employee
 
 @{
     ViewBag.Title = "Edit";
 }
 
 <h2>Edit</h2>
 
 <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
 <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
 
 @using (Html.BeginForm()) {
     @Html.ValidationSummary(true)
     <fieldset>
         <legend>Employee</legend>
 
         @Html.HiddenFor(model => model.Id)
 
         <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.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.DOB)
         </div>
         <div class="editor-field">
             @Html.EditorFor(model => model.DOB)
             @Html.ValidationMessageFor(model => model.DOB)
         </div>
 
         <p>
             <input type="submit" value="Save" />
         </p>
     </fieldset>
 }
 
 <div>
     @Html.ActionLink("Back to List", "Index")
 </div>
 
 Delete view code: 
 @model EntityFrameworkDemo.Models.Employee
 
 @{
     ViewBag.Title = "Delete";
 }
 
 <h2>Delete</h2>
 <h3>Are you sure you want to delete this?</h3>
 <fieldset>
     <legend>Employee</legend>
 
     <div class="display-label">Name</div>
     <div class="display-field">@Model.Name</div>
 
     <div class="display-label">Address</div>
     <div class="display-field">@Model.Address</div>
 </fieldset>
 @using (Html.BeginForm()) {
     <p>
         <input type="submit" value="Delete" /> |
         @Html.ActionLink("Back to List", "Index")
     </p>
 }
 
 
 Create view code:
 @model EntityFrameworkDemo.Models.Employee
 
 @{
     ViewBag.Title = "Create";
 }
 
 
 <h2>Create</h2>
 <script src="~/Scripts/jquery-1.4.1.min.js"></script>
 <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
 <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
 
 @using (Html.BeginForm()) {
     @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.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.DOB)
         </div>
         <div class="editor-field">
             @Html.EditorFor(model => model.DOB)
             @Html.ValidationMessageFor(model => model.DOB)
         </div>
 
         <p>
             <input type="submit" value="Create" />
         </p>
     </fieldset>
 }
 
 <div>
     @Html.ActionLink("Back to List", "Index")
 </div>
 
 

Build & run the solution, the output will be looking like:

clip_image018

Create view output:

clip_image020

Edit view output:

clip_image022

Delete view output:

clip_image024

To add primary/foreign key association we need to delete the employee model and create it freshly & then add the association

clip_image026

Right click on Department enitity & select the option : generate the datbase from model

It will generate the script & exeute the script in database, it will create both the tables with proper relationship

clip_image028

In my next article I will be explaining you the details implementation on Entity framework Database first approach.

Happy Coding

Tarun Kumar Chatterjee

Category : .Net

Author Info

Tarun Kumar Chatterjee
 
Net – Technology Specialist
 
Rate this article
 
Tarun has been working in IT Industry for over 12+ years. He holds a B-tech degree. He is passionate about learning and sharing the tricks and tips in Azure, .Net ...read more
 

How to Insert Update Taxonomy Fields (Multi Value) in SharePoint 2013 Programmatically

Sathish Nadarajan
 
Solution Architect
December 14, 2015
 
Rate this article
 
Views
16875

In the earlier articles, we saw many interesting facts about the Taxonomy Fields. In this article, let us see how to Insert, Update Taxonomy Field Programmatically using C#.

There are two types we need to consider. One is single value Taxonomy Field and the other is Multi Value Taxonomy Field.

Let us see how to insert a Single Value Taxonomy Field.

 SPListItem navigationListItem = navigationList.Items.Add();
 
                     SPField spfldTerm = navigationListItem.Fields.TryGetFieldByStaticName(<<StaticName of the Taxonomy Field>>);
                     TaxonomyField txfldTerm = (TaxonomyField)spfldTerm;
 
                     TaxonomyFieldValue taxonomyValue = new TaxonomyFieldValue(txfldTerm);
                     taxonomyValue.TermGuid = <<Term GUID>>.ToString();
                     taxonomyValue.Label = <<Term Name>>.Name;
 
                     navigationListItem[txfldTerm.Id] = taxonomyValue;
                     navigationListItem[txfldTerm.TextField] = taxonomyValue;
 

On the above code snippet, the Term GUID and Term Name will be the ID and Name of the Term.

Now, let us see how to insert a Multi Value Taxonomy Field. There is no much difference between insert and updating the Taxonomy field.

The Insert of Multi Value Taxonomy Field is as follows.

 for(int i=0; $i < arrayCount; $i++)
          {
 
             TaxonomyFieldValue GeoTagSecondaryFieldValue = new Microsoft.SharePoint.Taxonomy.TaxonomyFieldValue(GeoTagSecondaryField)
             GeoTagSecondaryFieldValue.TermGuid = array[$i]
             GeoTagSecondaryFieldValue.Label = array[$i]
 
             GeoTagSecondaryFieldValueCollection.Add($GeoTagSecondaryFieldValue)
 
          }
         GeoTagSecondaryField.SetFieldValue(newItem, GeoTagSecondaryFieldValueCollection) ;
 

The same can be done using the PowerShell as well.

 #Single Value :
 $newItem = $list.Items.Add()
 
         $BookShelvesField = [Microsoft.SharePoint.Taxonomy.TaxonomyField]$newItem.Fields["BookShelf"]
         $BookShelvesFieldValue = new-object Microsoft.SharePoint.Taxonomy.TaxonomyFieldValue($BookShelvesField)
         $BookShelvesFieldValue.TermGuid = $_.BookShelveTermGUID
         $BookShelvesFieldValue.Label = $_.BookShelveTermLabel
         $BookShelvesField.SetFieldValue($newItem, $BookShelvesFieldValue) 
 
 
 #And the Multi Value is like
 $GeoTagSecondaryCount = $GeoTagSecondaryTermIDArray.Length
 
           
   
          for($i=0; $i -lt $GeoTagSecondaryCount; $i++)
          {
             write-host $GeoTagSecondaryTermIDArray[$i]
 
             $GeoTagSecondaryFieldValue = new-object Microsoft.SharePoint.Taxonomy.TaxonomyFieldValue($GeoTagSecondaryField)
             $GeoTagSecondaryFieldValue.TermGuid = $GeoTagSecondaryTermIDArray[$i]
             $GeoTagSecondaryFieldValue.Label = $GeoTagSecondaryTermLabelArray[$i]
 
             $GeoTagSecondaryFieldValueCollection.Add($GeoTagSecondaryFieldValue)
 
          }
         $GeoTagSecondaryField.SetFieldValue($newItem, $GeoTagSecondaryFieldValueCollection)
 
         $newItem.Update() 
 
 

Happy Coding,

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

How to create a SPA MVC CRUD application using WebAPI, Angular JS, bootstrap & Entity framework

Tarun Kumar Chatterjee
 
Net – Technology Specialist
November 15, 2015
 
Rate this article
 
Views
10445

In this artifact let me explain you the steps to create a SPA MVC client application which will pull the data from WebAPI using Get or Post methods. Also, I have incorporated Angular JS, now a day it is most commonly used JavaScript framework. I am trying to cover Angular functionality called as ng-view to load partial views which is similar like usercontrol we have used in Asp.net application, also have tried to resolve the issues I faced at the time of implementing.

In traditional web applications, the client (browser) communicates with server by requesting a page. The server then processes the request and sends the HTML page to the client. In subsequent interactions with the page, for example the user navigates to a link or submits a form with data, a new request is sent to the server and the flow starts again. The server processes the request and sends a new page to the browser in response to the new action requested by the client.
But in Single-Page Applications (SPAs) the entire page is loaded into the browser after the initial request, subsequent interactions take place using Ajax requests. There is no need to reload the entire page. The SPA approach reduces the time taken by the application to respond to user actions, resulting in a more fluid experience.
clip_image002
Now we will learn this by creating a sample application. In this SPA example I will do CRUD operations on the Student table using the Web API and MVC.

The below DB script will create a table with Data needs to be executed in SQL Server database.

 USE [EmpDb]
 GO
 /****** Object:  Table [dbo].[Employees]    Script Date: 10/31/2015 23:24:53 ******/
 SET ANSI_NULLS ON
 GO
 SET QUOTED_IDENTIFIER ON
 GO
 CREATE TABLE [dbo].[Employees](
 	[EmployeeId] [int] IDENTITY(1,1) NOT NULL,
 	[FirstName] [nvarchar](20) NOT NULL,
 	[LastName] [nvarchar](20) NOT NULL,
 	[Description] [nvarchar](100) NOT NULL,
 	[Salary] [real] NOT NULL,
 	[Country] [nvarchar](50) NOT NULL,
 	[State] [nvarchar](50) NOT NULL,
 	[DateofBirth] [datetime] NOT NULL,
 	[IsActive] [bit] NOT NULL,
  CONSTRAINT [PK_dbo.Employees] PRIMARY KEY CLUSTERED 
 (
 	[EmployeeId] 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
 
 SET IDENTITY_INSERT [dbo].[Employees] ON
 INSERT [dbo].[Employees] ([EmployeeId], [FirstName], [LastName], [Description], [Salary], [Country], [State], [DateofBirth], [IsActive]) VALUES (1, N'Tarun1', N'Chatterjee1', N'Tarun1 Chatterjee1', 99999, N'IN', N'WB', CAST(0x00008403017F260F AS DateTime), 0)
 INSERT [dbo].[Employees] ([EmployeeId], [FirstName], [LastName], [Description], [Salary], [Country], [State], [DateofBirth], [IsActive]) VALUES (2, N'Tarun2', N'Chatterjee2', N'Tarun2 Chatterjee2', 49999.28, N'IN', N'WB', CAST(0x00008128017F2610 AS DateTime), 1)
 INSERT [dbo].[Employees] ([EmployeeId], [FirstName], [LastName], [Description], [Salary], [Country], [State], [DateofBirth], [IsActive]) VALUES (3, N'Tarun3', N'Chatterjee3', N'Tarun3 Chatterjee3', 234234240, N'IN', N'WB', CAST(0x0000A4CE0130DEE0 AS DateTime), 0)
 INSERT [dbo].[Employees] ([EmployeeId], [FirstName], [LastName], [Description], [Salary], [Country], [State], [DateofBirth], [IsActive]) VALUES (6, N'Tarun4', N'Chatterjee4', N'Tarun4 Chatterjee4', 889999, N'IN', N'WB', CAST(0x0000A4CF00000000 AS DateTime), 1)
 SET IDENTITY_INSERT [dbo].[Employees] OFF
 
 

Our database is ready. Now we will have to pull the data into the WebAPI with help of Entity Framework. Let see how it would be:

First, we will open Visual Studio 2013 & then click on New Project.

clip_image004

Select Web -> ASP.NET Web Application then provide a name & then click on OK.clip_image005

Right-click on the Models Folder & then select Add — > ADO.NET Entity Data Model.

clip_image007

Give the Item name as “ManageEmployee” & then Ok

clip_image009

clip_image011

Next, select table Name & then Finish

Now we will have to take Angular JS references. So, go to Package manager console and execute the below command to install Angular JS package to your solution.

PM> Install-Package angularjs

In RouteConfig add the following code

routes.MapRoute(

name: "Default",

url: "{controller}/{action}/{id}",

defaults: new { controller = "Employee", action = "Index", id = UrlParameter.Optional }

);

Then we will have to add a Web API Controller, so right-click on the controller folder & then select Add — > Controller.

clip_image013

clip_image015

Here is the generated EmployeeAPIController class

 using System;
 using System.Collections.Generic;
 using System.Data;
 using System.Data.Entity;
 using System.Data.Entity.Infrastructure;
 using System.Linq;
 using System.Net;
 using System.Net.Http;
 using System.Web.Http;
 using System.Web.Http.Description;
 using SpaWebApiMVC.Models;
 
 namespace SpaWebApiMVC.Controllers
 {
     public class EmployeeAPIController : ApiController
     {
         private EmpDbEntities db = new EmpDbEntities();
 
         // GET api/EmployeeAPI
         public IQueryable<Employee> GetEmployee()
         {
             return db.Employees;
         }
 
         // GET api/EmployeeAPI/5
         [ResponseType(typeof(Employee))]
         public IHttpActionResult GetEmployee(int id)
         {
             Employee employee = db.Employees.Find(id);
             if (employee == null)
             {
                 return NotFound();
             }
 
             return Ok(employee);
         }
 
         // PUT api/EmployeeAPI/5
         public IHttpActionResult PutEmployee(int id, Employee employee)
         {
             if (!ModelState.IsValid)
             {
                 return BadRequest(ModelState);
             }
 
             if (id != employee.EmployeeId)
             {
                 return BadRequest();
             }
 
             db.Entry(employee).State = EntityState.Modified;
 
             try
             {
                 db.SaveChanges();
             }
             catch (DbUpdateConcurrencyException)
             {
                 if (!EmployeeExists(id))
                 {
                     return NotFound();
                 }
                 else
                 {
                     throw;
                 }
             }
 
             return StatusCode(HttpStatusCode.NoContent);
         }
 
         // POST api/EmployeeAPI
         [ResponseType(typeof(Employee))]
         public IHttpActionResult PostEmployee(Employee employee)
         {
             if (!ModelState.IsValid)
             {
                 return BadRequest(ModelState);
             }
 
             db.Employees.Add(employee);
             db.SaveChanges();
 
             return CreatedAtRoute("DefaultApi", new { id = employee.EmployeeId }, employee);
         }
 
         // DELETE api/EmployeeAPI/5
         [ResponseType(typeof(Employee))]
         public IHttpActionResult DeleteEmployee(int id)
         {
             Employee employee = db.Employees.Find(id);
             if (employee == null)
             {
                 return NotFound();
             }
 
             db.Employees.Remove(employee);
             db.SaveChanges();
 
             return Ok(employee);
         }
 
         protected override void Dispose(bool disposing)
         {
             if (disposing)
             {
                 db.Dispose();
             }
             base.Dispose(disposing);
         }
 
         private bool EmployeeExists(int id)
         {
             return db.Employees.Count(e => e.EmployeeId == id) > 0;
         }
     }
 }
 
 

Again, right-click on the Controller folder & then select Add — > Controller.

Select MVC Controller Empty and then ADD

Give the controller name as “EmployeeController”

Now, we are ready to add a view.

clip_image017

Index.chtml Code will be like:

 @{
     ViewBag.Title = "SPA";
     Layout = "~/Views/Shared/_Layout.cshtml";
 }
 
 <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
 <body data-ng-app="ApplicationModule">
     <div>
         <div>
             <div>
                 <table cellpadding="5" cellspacing="6" width="100%" style="background-color:none; border:solid 4px black;">
                     <tr>
                         <td style="border: solid 1px ; width:170px; text-align:center;" class="glyphicon glyphicon-user"><a href="#/showEmployee"> Show All</a></td>
                         <td style="border: solid 1px ; width:170px; text-align:center;" class="glyphicon glyphicon-plus"><a href="#/addEmployee"> Add New</a></td>
                         <td></td>
                     </tr>
                 </table>
             </div>
             <div>
                 <div data-ng-view></div>
             </div>
         </div>
     </div>
 
 </body>
 
 @section scripts{
     <script type="text/javascript" src="@Url.Content("~/Scripts/angular.js")"></script>
     <script type="text/javascript" src="@Url.Content("~/Scripts/angular-route.min.js")"></script>
     <script type="text/javascript" src="@Url.Content("~/CustomScripts/Module.js")"></script>
     <script type="text/javascript" src="@Url.Content("~/CustomScripts/Services.js")" ></script>
     <script type="text/javascript" src="@Url.Content("~/CustomScripts/ShowEmployeeController.js")"></script>
     <script type="text/javascript" src="@Url.Content("~/CustomScripts/AddEmployeeController.js")"></script>
     <script type="text/javascript" src="@Url.Content("~/CustomScripts/EditEmployeeController.js")"></script>
     <script type="text/javascript" src="@Url.Content("~/CustomScripts/DeleteEmployeeController.js")"></script>
 } 
 
 

Here, we will add a partial view for all the modules. So right-click on Views then selects the Employee folder.

clip_image019

ShowEmployee.chtml code will be like:

<table cellpadding="4" cellspacing="4" width="100%" style="background-color:none; border:solid 2px ; padding-top:10px;">

<thead>

<tr style="background-color:none">

<th>Employee ID</th>

<th>FirstName</th>

<th>LastName</th>

<th>Description</th>

<th>Salary</th>

<th>Country</th>

<th>State</th>

<th>DateofBirth</th>

<th>IsActive</th>

</tr>

</thead>

<tbody>

<tr data-ng-repeat="emp in Employee">

<td>{{emp.employeeId}}</td>

<td>{{emp.firstName}}</td>

<td>{{emp.lastName}}</td>

<td>{{emp.description}}</td>

<td>{{emp.Salary}}</td>

<td>{{emp.country}}</td>

<td>{{emp.state}}</td>

<td>{{emp.dateofBirth}}</td>

<td>{{emp.isActive}}</td>

<td><a ng-href="#/editEmployee/{{emp.employeeId}}" class="glyphicon glyphicon-edit">Edit</a></td>

<td><a ng-href="#/deleteEmployee/{{emp.employeeId}}" class="glyphicon glyphicon-trash">Delete</a></td>

</tr>

</tbody>

</table>

Similarly, AddEmployee.chtml code will be like:

@{

ViewBag.Title = "Add New Employee";

}

<table><tr><td height="10px"></td></tr></table>

<table cellpadding="4" cellspacing="4" width="70%" align="center" style="background-color:none;

border:solid 2px ; padding-top:20px;">

<tr>

<td colspan="3" style="background-color:gray; font-size:18pt;

font-weight:bold; height:30px; text-align:center;">

Add New Employee

</td>

</tr>

<tr>

<td style="text-align:right;">Employee ID</td>

<td><input type="text" ng-model="EmployeeId" /> </td>

</tr>

<tr>

<td style="text-align:right;">FirstName</td>

<td><input type="text" ng-model="FirstName" /> </td>

</tr>

<tr>

<td style="text-align:right;">LastName</td>

<td><input type="text" ng-model="LastName" /> </td>

</tr>

<tr>

<td style="text-align:right;">Description</td>

<td><input type="text" ng-model="Description" /> </td>

</tr>

<tr>

<td style="text-align:right;">Salary</td>

<td><input type="text" ng-model="Salary" /> </td>

</tr>

<tr>

<td style="text-align:right;">Country</td>

<td><input type="text" ng-model="Country" /> </td>

</tr>

<tr>

<td style="text-align:right;">State</td>

<td><input type="text" ng-model="State" /> </td>

</tr>

<tr>

<td style="text-align:right;">DateofBirth</td>

<td><input type="text" ng-model="DateofBirth" /> </td>

</tr>

<tr>

<td style="text-align:right;">IsActive</td>

<td><input type="text" ng-model="IsActive" /> </td>

</tr>

<tr>

<td></td>

<td>

<input type="button" value="Save" data-ng-click="save()" />

</td>

</tr>

</table>

EditEployee.chtml code will be like:

@{

ViewBag.Title = "Edit Employee";

}

<table><tr><td height="10px"></td></tr></table>

<table cellpadding="4" cellspacing="4" width="70%" align="center" style="background-color: none; border:solid 2px black; padding-top:20px;">

<tr><td colspan="3" style="background-color:none; font-size:18pt; font-weight:bold; height:30px; text-align:center;">Edit Employee</td></tr>

<tr>

<td style="text-align:right;">Employee ID</td>

<td><input type="text" ng-model="Employee.employeeId" /> </td>

</tr>

<tr>

<td style="text-align:right;">FirstName</td>

<td><input type="text" ng-model="Employee.firstName" /> </td>

</tr>

<tr>

<td style="text-align:right;">LastName</td>

<td><input type="text" ng-model="Employee.lastName" /> </td>

</tr>

<tr>

<td style="text-align:right;">Description</td>

<td><input type="text" ng-model="Employee.description" /> </td>

</tr>

<tr>

<td style="text-align:right;">Salary</td>

<td><input type="text" ng-model="Employee.salary" /> </td>

</tr>

<tr>

<td style="text-align:right;">Country</td>

<td><input type="text" ng-model="Employee.country" /> </td>

</tr>

<tr>

<td style="text-align:right;">State</td>

<td><input type="text" ng-model="Employee.state" /> </td>

</tr>

<tr>

<td style="text-align:right;">DateofBirth</td>

<td><input type="text" ng-model="Employee.dateofBirth" /> </td>

</tr>

<tr>

<td style="text-align:right;">IsActive</td>

<td><input type="text" ng-model="Employee.isActive" /> </td>

</tr>

<tr>

<td></td>

<td>

<input type="button" value="Save" ng-click="save()" />

<br />

<div>{{error}}</div>

</td>

</tr>

</table>

DeleteEmployee.chtml code will be like:

@{

ViewBag.Title = "Delete Employee";

}

<table><tr><td height="10px"></td></tr></table>

<table cellpadding="4" cellspacing="4" width="70%" align="center" style="background-color: none; border:solid 2px black; padding-top:20px;">

<tr><td colspan="3" style="background-color:none; font-size:18pt; font-weight:bold; height:30px; text-align:center;">Delete Employee</td></tr>

<tr>

<td style="text-align:right;">Employee ID</td>

<td>{{Employee.employeeId}} </td>

</tr>

<tr>

<td style="text-align:right;">FirstName</td>

<td> {{Employee.firstName}} </td>

</tr>

<tr>

<td style="text-align:right;">LastName</td>

<td>{{Employee.lastName}} </td>

</tr>

<tr>

<td style="text-align:right;">Description</td>

<td>{{Employee.description}} </td>

</tr>

<tr>

<td style="text-align:right;">Salary</td>

<td>{{Employee.salary}} </td>

</tr>

<tr>

<td style="text-align:right;">Country</td>

<td>{{Employee.country}} </td>

</tr>

<tr>

<td style="text-align:right;">State</td>

<td>{{Employee.state}} </td>

</tr>

<tr>

<td style="text-align:right;">DateofBirth</td>

<td>{{Employee.dateofBirth}} </td>

</tr>

<tr>

<td style="text-align:right;">IsActive</td>

<td>{{Employee.isActive}} </td>

</tr>

<tr>

<td></td>

<td>

<input type="button" value="Delete" ng-click="delete()" />

</td>

</tr>

</table>

Next, we will have to add the following code in EmployeeController.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

namespace SpaWebApiMVC.Controllers

{

public class EmployeeController : Controller

{

//

// GET: /Employee/

public ActionResult Index()

{

return View();

}

public ActionResult AddEmployee()

{

return PartialView("AddEmployee");

}

public ActionResult ShowEmployee()

{

return PartialView("ShowEmployee");

}

public ActionResult EditEmployee()

{

return PartialView("EditEmployee");

}

public ActionResult DeleteEmployee()

{

return PartialView("DeleteEmployee");

}

}

}

Again, we will have to add a new folder called “CustomScripts”, to the solution which will have the custom controllers for all the individual modules.

So, we need to add the following JavaScript files within “CustomScripts” folder.

  • Module.js
  • Services.js
  • ShowEmployeeController.js
  • AddEmployeeController.js
  • EditEmployeeController.js
  • DeleteEmployeeController.js

Module.JS code will be like:

var app = angular.module("ApplicationModule", ["ngRoute"]);

app.factory("ShareData", function () {

return { value: 0 }

});

//Showing Routing

app.config([‘$routeProvider’, ‘$locationProvider’, function ($routeProvider, $locationProvider) {

$routeProvider.when(‘/showEmployee’,

{

templateUrl: ‘Employee/ShowEmployee’,

controller: ‘ShowEmployeeController’

});

$routeProvider.when(‘/addEmployee’,

{

templateUrl: ‘Employee/AddEmployee’,

controller: ‘AddEmployeeController’

});

$routeProvider.when("/editEmployee/:id",

{

templateUrl: ‘Employee/EditEmployee’,

controller: ‘EditEmployeeController’

});

$routeProvider.when(‘/deleteEmployee/:id’,

{

templateUrl: ‘Employee/DeleteEmployee’,

controller: ‘DeleteEmployeeController’

});

$routeProvider.otherwise(

{

redirectTo: ‘/showEmployee’

});

//This can be used to remove # from URL

//$locationProvider.html5Mode(true).hashPrefix(‘!’)

}]);

Services.js code will be like:

app.service("SPACRUDService", function ($http) {

//Read all Employee

this.getEmployees = function () {

return $http.get("/api/EmployeeAPI");

};

//Fundction to Read Employee by Employee ID

this.getEmployee = function (id) {

return $http.get("/api/EmployeeAPI/" + id);

};

//Function to create new Employee

this.post = function (Employee) {

var request = $http({

method: "post",

url: "/api/EmployeeAPI",

data: Employee

});

return request;

};

//Edit Employee By Employee ID

this.put = function (id, Employee) {

var request = $http({

method: "put",

url: "/api/EmployeeAPI/" + id,

data: Employee

});

return request;

};

//Delete Employee By Employee ID

this.delete = function (id) {

var request = $http({

method: "delete",

url: "/api/EmployeeAPI/" + id

});

return request;

};

});

ShowEmployeeController.js code will be like:

app.controller(‘ShowEmployeeController’, function ($scope, $location, $routeParams, SPACRUDService, ShareData) {

loadEmployee();

function loadEmployee() {

var emp = SPACRUDService.getEmployees();

emp.then(function (pl) {

$scope.Employee = pl.data;

console.log(JSON.stringify($scope.Employee));

},

function (errorPl) {

$scope.error = errorPl;

});

}

});

AddEmployeeController.js code will be like:

app.controller(‘AddEmployeeController’, function ($scope, SPACRUDService) {

$scope.EmployeeId = 0;

$scope.save = function () {

var emp = {

EmployeeId: $scope.EmployeeId,

FirstName: $scope.FirstName,

LastName: $scope.LastName,

Description: $scope.Description,

Salary: $scope.Salary,

Country: $scope.Country,

State: $scope.State,

DateofBirth: $scope.DateofBirth,

IsActive: $scope.IsActive

};

var val = SPACRUDService.post(emp);

val.then(function (pl) {

alert("Employee Saved Successfully.");

},

function (errorPl) {

$scope.error = ‘failure loading Employee’, errorPl;

});

};

});

EditEmployeeController.js code will be like:

app.controller("EditEmployeeController", function ($scope, $location, $routeParams,ShareData, SPACRUDService) {

getEmployee();

function getEmployee() {

ShareData.value = $routeParams.id;

var emp = SPACRUDService.getEmployee(ShareData.value);

emp.then(function (pl) {

$scope.Employee = pl.data;

debugger;

},

function (errorPl) {

$scope.error = ‘failure loading Employee’, errorPl;

});

}

$scope.save = function () {

var emp = {

EmployeeId: $scope.Employee.employeeId,

FirstName: $scope.Employee.firstName,

LastName: $scope.Employee.lastName,

Description: $scope.Employee.description,

Salary: $scope.Employee.salary,

Country: $scope.Employee.country,

State: $scope.Employee.state,

DateofBirth: $scope.Employee.dateofBirth,

IsActive: $scope.Employee.isActive

};

var val = SPACRUDService.put($scope.Employee.employeeId, emp);

val.then(function (pl) {

$location.path("/showEmployee");

},

function (errorPl) {

$scope.error = ‘failure loading Employee’, errorPl;

});

};

});

DeleteEmployeeController.js code will be like:

app.controller(“DeleteEmployeeController”, function ($scope, $location, $routeParams, ShareData, SPACRUDService) {

getEmployee();

function getEmployee() {

ShareData.value = $routeParams.id;

var emp = SPACRUDService.getEmployee(ShareData.value);

emp.then(function (pl) {

$scope.Employee = pl.data;

},

function (errorPl) {

$scope.error = ‘failure loading Employee’, errorPl;

});

}

$scope.delete = function () {

var promiseDeleteEmployee = SPACRUDService.delete(ShareData.value);

promiseDeleteEmployee.then(function (pl) {

$location.path(“/showEmployee”);

},

function (errorPl) {

$scope.error = ‘failure loading Employee’, errorPl;

});

};

});

Now rebuild the solution and run. Following is the output of ShowEmployee page :

clip_image021

Edit page output :

clip_image023

Delete page output :

clip_image025

So, we can see here in each url is having # and to ignore # from the url we need to modify our apps config, it now has Angular’s $locationProvider module as a dependency and we need to enable hashPrefix and html5mode functions. That’s it.

Enable the following code in Module.js

$locationProvider.html5Mode(true).hashPrefix(‘!’);

Our URL’s look better, but hit refresh (F5) & it will throw the 404 error

clip_image027

HTML5 mode is working, but only in a very superficial way. A refresh of the page is sending the full URL to the server (as we have removed the #) which doesn’t know what to do. We can fix this by reconfiguring MVC’s RouteCollection properly. We need to be explicit about the route for each of our views, and then add a catch-all which sends all other URL’s to our landing page, to be handled by Angular.

Update the RegisterRoutes method inside App_Start — > RouteConfig.cs like :

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Routing;

namespace SpaWebApiMVC

{

public class RouteConfig

{

public static void RegisterRoutes(RouteCollection routes)

{

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(

name: "ShowEmployee",

url: "Employee/ShowEmployee",

defaults: new { controller = "Employee", action = "ShowEmployee" }

);

routes.MapRoute(

name: "AddEmployee",

url: "Employee/AddEmployee",

defaults: new { controller = "Employee", action = "AddEmployee", id = UrlParameter.Optional }

);

routes.MapRoute(

name: "EditEmployee",

url: "Employee/EditEmployee/{id}",

defaults: new { controller = "Employee", action = "EditEmployee", id = UrlParameter.Optional }

);

routes.MapRoute(

name: "DeleteEmployee",

url: "Employee/DeleteEmployee/{id}",

defaults: new { controller = "Employee", action = "DeleteEmployee", id = UrlParameter.Optional }

);

routes.MapRoute(

name: "Default",

url: "{*url}",

defaults: new { controller = "Employee", action = "Index", id = UrlParameter.Optional }

);

}

}

}

Now change the below line of codes in ShowEmployee.chtml

<td><a ng-href="editEmployee/{{emp.employeeId}}" class="glyphicon glyphicon-edit">Edit</a></td>

<td><a ng-href="deleteEmployee/{{emp.employeeId}}" class="glyphicon glyphicon-trash">Delete</a></td>

And the below lines in Index.chtml

<td style="border: solid 1px ; width:170px; text-align:center;" class="glyphicon glyphicon-user"><a href="showEmployee"> Show All</a></td>

<td style="border: solid 1px ; width:170px; text-align:center;" class="glyphicon glyphicon-plus"><a href="addEmployee"> Add New</a></td>

Debug the site again, browse around, and test the back/refresh buttons, everything should be working properly now.

Hope, this will help you. If you have any question feel free to write me a note in comments, I will try to explain.

Happy Coding

Tarun Kumar Chatterjee

Category : .Net, Ajax, Angular

Author Info

Tarun Kumar Chatterjee
 
Net – Technology Specialist
 
Rate this article
 
Tarun has been working in IT Industry for over 12+ years. He holds a B-tech degree. He is passionate about learning and sharing the tricks and tips in Azure, .Net ...read more
 

Leave a comment