Here are the steps,
Step 1
Create a table, for example, see below with a snapshot.
Step 2
->Open Visual studio and take a new project.
->Choose ASP.NET Web Application and give name Ex.CRUDWebApiExam and click ok.
We have to create the first Web API, so we choose the Web API option and click OK.
Step 3
Now we have to add a class so for this, we right-click of web API project and add ADO.NET Entity Data Model,
Add EF Designer from the database and click the Next button.
Add click new connection option and give the server name and select database and click Test Connection and click ok.
Click Next and select the table which you want and click ok.
Click Finish.
Step 4
Now we have to add Web API controller, So right-click on controllers folder,
Select 'Web Api Controller with views, using Entity framework'.
Click Add.
Select the Model Class Name Exam. Customer(In my project).
Select Data context class, Exam. SystemTestEntity (In my project).
Give the Controller Name Exam. Customer.
Click Add.
Note - After that it automatically generates CustomerController.cs like this.
- using System.Data.Entity;
- using System.Data.Entity.Infrastructure;
- using System.Linq;
- using System.Net;
- using System.Web.Http;
- using System.Web.Http.Description;
- using CRUDWebApiExam.Models;
-
- namespace CRUDWebApiExam.Controllers {
- public class CustomersController: ApiController {
- private SystemTestEntities db = new SystemTestEntities();
-
-
- public IQueryable < Customer > GetCustomer() {
- return db.Customer;
- }
-
-
- [ResponseType(typeof(Customer))]
- public IHttpActionResult GetCustomer(int id) {
- Customer customer = db.Customer.Find(id);
- if (customer == null) {
- return NotFound();
- }
-
- return Ok(customer);
- }
-
-
- [ResponseType(typeof(void))]
- public IHttpActionResult PutCustomer(int id, Customer customer) {
- if (!ModelState.IsValid) {
- return BadRequest(ModelState);
- }
-
- if (id != customer.CustomerId) {
- return BadRequest();
- }
-
- db.Entry(customer).State = EntityState.Modified;
-
- try {
- db.SaveChanges();
- } catch (DbUpdateConcurrencyException) {
- if (!CustomerExists(id)) {
- return NotFound();
- } else {
- throw;
- }
- }
-
- return StatusCode(HttpStatusCode.NoContent);
- }
-
-
- [ResponseType(typeof(Customer))]
- public IHttpActionResult PostCustomer(Customer customer) {
- if (!ModelState.IsValid) {
- return BadRequest(ModelState);
- }
-
- db.Customer.Add(customer);
- db.SaveChanges();
-
- return CreatedAtRoute("DefaultApi", new { id = customer.CustomerId }, customer);
- }
-
-
- [ResponseType(typeof(Customer))]
- public IHttpActionResult DeleteCustomer(int id) {
- Customer customer = db.Customer.Find(id);
- if (customer == null) {
- return NotFound();
- }
-
- db.Customer.Remove(customer);
- db.SaveChanges();
-
- return Ok(customer);
- }
-
- protected override void Dispose(bool disposing) {
- if (disposing) {
- db.Dispose();
- }
- base.Dispose(disposing);
- }
-
- private bool CustomerExists(int id) {
- return db.Customer.Count(e => e.CustomerId == id) > 0;
- }
- }
- }
And run the Web Api project and see the result like this below,
Step 5
->Now we have to add an MVC project for consuming the web API services, So first we have to add a model class, so here we took Customer class. For this, we right click models folder and add class and give the name, for ex. Customer.cs.
- using System;
- using System.ComponentModel.DataAnnotations;
-
- namespace MVCPersatantion.Models {
- public class Customer {
- [Display(Name = "CustomerId")]
- public int CustomerId { get;
- set; }
- [Display(Name = "Name")]
- public string Name { get;
- set; }
- [Display(Name = "Address")]
- public string Address { get;
- set; }
- [Display(Name = "MobileNo")]
- public string MobileNo { get;
- set; }
- [Display(Name = "Birthdate")]
- [DataType(DataType.Date)]
- public DateTime Birthdate { get;
- set; }
- [Display(Name = "EmailId")]
- public string EmailId { get;
- set; }
- }
- }
->Ok we added customer class so next thing is we have to add ViewModel folder and add a class for exm.CustomerViewModel.cs,
- using MVCPersatantion.Models;
- namespace MVCPersatantion.ViewModel {
- public class CustomerViewModel {
- public Customer customer { get;
- set; }
- }
- }
Step 6
We have to add a class for consuming the web service for this thing so we add a class and give the name exam. CustomerClient.cs for this just right click on Models folder and add below code.
- using System;
- using System.Collections.Generic;
- using System.Net.Http;
- using System.Net.Http.Headers;
-
- namespace MVCPersatantion.Models {
- public class CustomerClient {
- private string Base_URL = "http://localhost:30110/api/";
-
- public IEnumerable < Customer > findAll() {
- try {
- HttpClient client = new HttpClient();
- client.BaseAddress = new Uri(Base_URL);
- client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- HttpResponseMessage response = client.GetAsync("customers").Result;
-
- if (response.IsSuccessStatusCode)
- return response.Content.ReadAsAsync < IEnumerable < Customer >> ().Result;
- return null;
- } catch {
- return null;
- }
- }
- public Customer find(int id) {
- try {
- HttpClient client = new HttpClient();
- client.BaseAddress = new Uri(Base_URL);
- client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- HttpResponseMessage response = client.GetAsync("customers/" + id).Result;
-
- if (response.IsSuccessStatusCode)
- return response.Content.ReadAsAsync < Customer > ().Result;
- return null;
- } catch {
- return null;
- }
- }
- public bool Create(Customer customer) {
- try {
- HttpClient client = new HttpClient();
- client.BaseAddress = new Uri(Base_URL);
- client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- HttpResponseMessage response = client.PostAsJsonAsync("customers", customer).Result;
- return response.IsSuccessStatusCode;
- } catch {
- return false;
- }
- }
- public bool Edit(Customer customer) {
- try {
- HttpClient client = new HttpClient();
- client.BaseAddress = new Uri(Base_URL);
- client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- HttpResponseMessage response = client.PutAsJsonAsync("customers/" + customer.CustomerId, customer).Result;
- return response.IsSuccessStatusCode;
- } catch {
- return false;
- }
- }
- public bool Delete(int id) {
- try {
- HttpClient client = new HttpClient();
- client.BaseAddress = new Uri(Base_URL);
- client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- HttpResponseMessage response = client.DeleteAsync("customers/" + id).Result;
- return response.IsSuccessStatusCode;
- } catch {
- return false;
- }
- }
- }
- }
Note - We see here that in every method some codes are repeating, so we can declare only one time and we can use that but I wrote a separate one for understanding purposes
->First we see in the first line I gave base URL. see below
private string Base_URL = "http://localhost:30110/api/";
So I want to say that this base_url value is the web API service URL,
->After we write methods for Insert, Update, Delete, Select one by one
Step 7
We have to add a controller, so for this right-click on the Controllers folder and add a controller and give the name for ex.Customers and write the code and call the service client method.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using MVCPersatantion.Models;
- using MVCPersatantion.ViewModel;
-
- namespace MVCPersatantion.Controllers {
- public class CustomerController: Controller {
-
- public ActionResult Index() {
- CustomerClient CC = new CustomerClient();
- ViewBag.listCustomers = CC.findAll();
-
- return View();
- }
- [HttpGet]
- public ActionResult Create() {
- return View("Create");
- }
- [HttpPost]
- public ActionResult Create(CustomerViewModel cvm) {
- CustomerClient CC = new CustomerClient();
- CC.Create(cvm.customer);
- return RedirectToAction("Index");
- }
-
- public ActionResult Delete(int id) {
- CustomerClient CC = new CustomerClient();
- CC.Delete(id);
- return RedirectToAction("Index");
- }
- [HttpGet]
- public ActionResult Edit(int id) {
- CustomerClient CC = new CustomerClient();
- CustomerViewModel CVM = new CustomerViewModel();
- CVM.customer = CC.find(id);
- return View("Edit", CVM);
- }
- [HttpPost]
- public ActionResult Edit(CustomerViewModel CVM) {
- CustomerClient CC = new CustomerClient();
- CC.Edit(CVM.customer);
- return RedirectToAction("Index");
- }
- }
- }
Step 8:
->Now we have to create a view page so first create the Index page.
->For this right-click on index method in Customer controller and add view and write below code
Index.cshtml- @{ViewBag.Title = "Index";}
- <h2>Index</h2>
- <div align="center">
- <a href="@Url.Action(" Create"," Customer ")"> Add New Customer </a> <br /> <br />
- <table cellpadding="2" class="table" cellspacing="2" border="1">
- <tr class="btn-primary">
- <th> CustomerId </th>
- <th> Name </th>
- <th> Address </th>
- <th> MobileNo </th>
- <th> Birthdate </th>
- <th> EmailId </th>
- <th> Action </th>
- </tr>
- @foreach(var Cust in ViewBag.listCustomers) { <tr class="btn-success">
- <td>@Cust.CustomerId </td>
- <td>@Cust.Name </td>
- <td>@Cust.Address </td>
- <td>@Cust.MobileNo </td>
- <td>@Cust.Birthdate.ToString("dd/MM/yyyy") </td>
- <td>@Cust.EmailId </td>
- <td>
- <a onclick="return confirm('Do you want to Delete?')" href="@Url.Action(" Delete "," Customer ",new {id= Cust.CustomerId})">Delete</a> || <a href="@Url.Action(" Edit "," Customer ",new { id = Cust.CustomerId
- })
- ">Edit</a> </td>
- </tr>
- }
- </table>
- </div>
->Now we have to create a Create page.
->For this right-click on create method in Customer controller and add view and write below code.
Create.cshtml
- @{ViewBag.Title = "Create";
- }
- @model MVCPersatantion.ViewModel.CustomerViewModel
- <h2> Create </h2>
- <div align="center">
- @using(Html.BeginForm("create", "Customer", FormMethod.Post))
- {
- <table class="table">
- <tr>
- <td>@Html.LabelFor(model => model.customer.Name) </td>
- <td>@Html.TextBoxFor(model => model.customer.Name) </td>
- </tr>
- <tr>
- <td>@Html.LabelFor(model => model.customer.Address) </td>
- <td>@Html.TextBoxFor(model => model.customer.Address) </td>
- </tr>
- <tr>
- <td>@Html.LabelFor(model => model.customer.MobileNo) </td>
- <td>@Html.TextBoxFor(model => model.customer.MobileNo) </td>
- </tr>
- <tr>
- <td>@Html.LabelFor(model => model.customer.Birthdate) </td>
- <td>@Html.TextBoxFor(model => model.customer.Birthdate) </td>
- </tr>
- <tr>
- <td>@Html.LabelFor(model => model.customer.EmailId) </td>
- <td>@Html.TextBoxFor(model => model.customer.EmailId) </td>
- </tr>
- <tr>
- <td></td>
- <td><input type="submit" value="Save" /></td>
- </tr>
- </table>
- } </div>
->Now we have to create edit view page.
->For this right-click on Edit method in Customer controller and add view and write below code
Edit.cshtml- @ { ViewBag.Title = "Edit";}
- @model MVCPersatantion.ViewModel.CustomerViewModel
- <h2> Edit </h2>
- <div align="center" width="500px"> @using(Html.BeginForm("Edit", "Customer", FormMethod.Post))
- {
- <table class="table" width="400px" cellpadding="20">
- <tr class="btn-default">
- <td> @Html.LabelFor(model => model.customer.Name) </td>
- <td> @Html.TextBoxFor(model => model.customer.Name) </td>
- </tr>
- <tr>
- <td> @Html.LabelFor(model => model.customer.Address) </td>
- <td> @Html.TextBoxFor(model => model.customer.Address) </td>
- </tr>
- <tr>
- <td> @Html.LabelFor(model => model.customer.MobileNo) </td>
- <td> @Html.TextBoxFor(model => model.customer.MobileNo) </td>
- </tr>
- <tr>
- <td> @Html.LabelFor(model => model.customer.Birthdate) </td>
- <td> @Html.TextBoxFor(model => model.customer.Birthdate) </td>
- </tr>
- <tr>
- <td> @Html.LabelFor(model => model.customer.EmailId) </td>
- <td> @Html.TextBoxFor(model => model.customer.EmailId) </td>
- </tr>
- <tr>
- <td> </td>
- <td> <input type="submit" value="Save" /> & nbsp; <a class="btn-primary" href="@Url.Action(" Index "," Customer ")"> Back </a> @Html.HiddenFor(model => model.customer.CustomerId) </td>
- </tr>
- </table>
- } </div>
->Finally we have completed it so now we execute the program but one thing here is we have to run both web API and MVC projects so first, we have to set this that runs both programs.
->So for a set this, we right-click on the solution and go to properties like this.
->So next, we go to Startup Project option and select the multiple startup projects and go to Action and set 'Start' for both project, that's all
->So finally execute the program and see the result and see the functionality of crud operation.
First, see for the select result,
See for the Insert,
See for Update,
See for delete,
Click ok.
I hope you enjoyed this. Thank you for looking at the example.