Hi, Today I will explain how to perform CRUD operation in MVC using Web API and angular Js. Let us see step by step.
Step 1
First open Visual studio >>FIle >> New Project >> Select we application >> Choose Web APi and click ok
Step 2
Go to controller folder and right click, Add >> Controller >> Select API Controller
After that click Add button
Step3
Open SQL server and create a table like Employee
Step4
Now we will add entity framework. So for this go the Model folder >> Right Click and select Add >> New item >> Select ADO. NET Entity Data Model
Click Add Button
Then Click Next buttonNow,
select the "New connection" button and give the server name and our SQL credentials after selecting the database.
Step 6
Now we have to add one more project to Consume the service. So for that right click of the project solution and add a new project and select MVC and add Web Application.
Now right click of the controller folder and add a controller and write an action method and add a view
Here, We will consume the service using angular js so now we have to create some angular js file so first we will create a folder in the script folder.
After that add three files like below image
First, open the App.js file and copy and paste below code
After that open Employee.js file and copy and paste below code
Step 7
Run the project, however, we have to run both projects at one time so for this, so we have to set some changes. Right-click on the solution project and go to properties. Here, check the Multiple Startup Projects option and click the Apply button.
Now, we see an output with an unexpected error.
Now again run the project and see the output
This error is called CORS. So first, we have to know what CORS is and how to resolve this problem.
After that, goto App_Start folder in Web API project and then WebApiConfig.cs class. Here, modify the Register method with the below code.
Step 1
First open Visual studio >>FIle >> New Project >> Select we application >> Choose Web APi and click ok
Step 2
Go to controller folder and right click, Add >> Controller >> Select API Controller
After that click Add button
Step3
Open SQL server and create a table like Employee
Step4
Now we will add entity framework. So for this go the Model folder >> Right Click and select Add >> New item >> Select ADO. NET Entity Data Model
Click Add Button
Then Click Next buttonNow,
select the "New connection" button and give the server name and our SQL credentials after selecting the database.
Click ok
After that, select our existing table like in the below image.
click finish
Step5
Now open the api controller and copy and paste below code for crud operation
namespace CRUDWithAngularJs.Controllers
{
[RoutePrefix("api/Employee")]
public class EmployeeAPIController : ApiController
{
ExampleDBEntities objEntity = new ExampleDBEntities();
[HttpGet]
[Route("BindEmpDetails")]
public List<Employee>
BindEmp()
{
List<Employee>
empDetail = new List<Employee>();
empDetail =
objEntity.Employees.ToList();
return empDetail;
}
[HttpPost]
[Route("InsertEmp")]
public string InserEmp(Employee
objEmployee)
{
objEntity.Employees.Add(objEmployee);
int i = objEntity.SaveChanges();
if (i > 0)
{
return "Insertion successfull";
}
else
{
return "Insertion Faild";
}
}
[HttpPost]
[Route("UpdateEmp")]
public string UpdateEmp(Employee
objEmpDetails)
{
string objPost = string.Empty;
string message = "";
Employee objEmp = new Employee();
objEmp =
objEntity.Employees.Find(objEmpDetails.EmployeeId);
if (objEmp != null)
{
objEmp.EmpName =
objEmpDetails.EmpName;
objEmp.Address =
objEmpDetails.Address;
objEmp.EmailId =
objEmpDetails.EmailId;
objEmp.MobileNo =
objEmpDetails.MobileNo;
objEmp.DeptName =
objEmpDetails.DeptName;
}
int i = this.objEntity.SaveChanges();
if (i > 0)
{
message = "Updation
success";
}
else
{
message = "Updation
faild";
}
return message;
}
[HttpGet]
[Route("EmpDelete")]
public string JobSeekerEduDelete(string EmpId)
{
int? id = Convert.ToInt32(EmpId);
string strMsg = string.Empty;
if (id != null)
{
var objEmp = objEntity.Employees.Find(id);
objEntity.Employees.Remove(objEmp);
int i = objEntity.SaveChanges();
if (i > 0)
{
strMsg = "Deletion
Successful";
}
else
{
strMsg = "Deletion
Faild";
}
}
return strMsg;
}
}
}
Step 6
Now we have to add one more project to Consume the service. So for that right click of the project solution and add a new project and select MVC and add Web Application.
Now right click of the controller folder and add a controller and write an action method and add a view
public ActionResult Index()
{
return View();
}
Here, We will consume the service using angular js so now we have to create some angular js file so first we will create a folder in the script folder.
After that add three files like below image
var app = angular.module("MyApp", []);
After that open Service.js file and
paste below code
app.factory('CommonUrlService', function ($http)
{
var fac = { };
fac.GetEmpDetails = function() {
return $http.get('http://localhost:28907/api/Employee/BindEmpDetails');
};
fac.InsertEmpRecords = function(objEmpDetails) {
var request = $http({
method: "POST",
url: 'http://localhost:28907/api/Employee/InsertEmp',
data: objEmpDetails
});
return request;
};
fac.UpdateEmpRecords = function(objEmpDetails) {
var request = $http({
method: "POST",
url: 'http://localhost:28907/api/Employee/UpdateEmp',
data: objEmpDetails
});
return request;
};
fac.DeleteEmp = function(EmpId) {
var request = $http({
method: "get",
url: 'http://localhost:28907/api/Employee/EmpDelete?EmpId=' + EmpId
});
return request;
};
return fac;
});
After that open Employee.js file and copy and paste below code
app.controller('EmployeeController', function ($scope,
CommonUrlService) {
$scope.btnText = "Save";
CommonUrlService.GetEmpDetails().then(function (d) {
$scope.EmployeeList = d.data;
});
$scope.SaveUpdateEmp = function () {
var employee = {
EmployeeId: $scope.EmployeeId,
FirstName: $scope.firstName,
LastName: $scope.lastName,
EmpCode: $scope.empCode,
Position: $scope.position,
Office: $scope.office
}
if ($scope.btnText == "Save") {
var saveStudent =
CommonUrlService.InsertEmpRecords(employee);
saveStudent.then(function (response) {
if (response.data != "") {
alert(response.data);
CommonUrlService.GetEmpDetails().then(function (d) {
$scope.EmployeeList =
d.data;
});
} else {
alert("Some
error");
}
}, function (error) {
console.log("Error: " + error);
});
} else {
var UpdateEmployee =
CommonUrlService.UpdateEmpRecords(employee);
UpdateEmployee.then(function (response) {
if (response.data != "") {
alert(response.data);
$scope.btnText = "Save";
CommonUrlService.GetEmpDetails().then(function (d) {
$scope.EmployeeList =
d.data;
});
} else {
alert("Some
error");
}
}, function (error) {
console.log("Error: " + error);
});
}
}
$scope.GetEmployeeByID = function (emp) {
$scope.EmployeeId = emp.EmployeeId;
$scope.firstName = emp.FirstName;
$scope.lastName = emp.LastName;
$scope.empCode = emp.EmpCode;
$scope.position = emp.Position;
$scope.office = emp.Office;
$scope.btnText = "Update";
}
$scope.DeleteEmployee = function (emp) {
var deleteStudent =
CommonUrlService.DeleteEmp(emp.EmployeeId);
deleteStudent.then(function (response) {
if (response.data != "") {
alert(response.data);
CommonUrlService.GetEmpDetails().then(function (d) {
$scope.EmployeeList =
d.data;
});
} else {
alert("Some
error");
}
}, function (error) {
console.log("Error: " + error);
});
}
})
Step 7
Run the project, however, we have to run both projects at one time so for this, so we have to set some changes. Right-click on the solution project and go to properties. Here, check the Multiple Startup Projects option and click the Apply button.
Now, we see an output with an unexpected error.
Now again run the project and see the output
This error is called CORS. So first, we have to know what CORS is and how to resolve this problem.
According to Wikipedia,
Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources (e.g. fonts) on a web page to be requested from another domain outside the domain from which the first resource was served.
For more details, click this link.
Now, let us learn how to resolve this problem.
So for this, we have to download CORS in the Web API project. Go to NuGet Package Manager and download the following file.
After that, goto App_Start folder in Web API project and then WebApiConfig.cs class. Here, modify the Register method with the below code.
var cors = new EnableCorsAttribute("*", "*", "*");// origins, headers, methods
config.EnableCors(cors);
Now, save changes and run the project to see the final output.
Check functionality
Thanks
No comments:
Post a Comment