In this Blog, you can learn ASP.NET WEB API CRUD Operations With ASP.NET MVC And Entity Framework, and you can also have the complete source code the application.
Source Code – CrudApiController – ApiController Code
using AspWebApi_Crud.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Mvc;
namespace AspWebApi_Crud.Controllers
{
public class CrudApiController : ApiController
{
web_api_crud_dbEntities db = new web_api_crud_dbEntities();
[System.Web.Http.HttpGet]
public IHttpActionResult GetEmployees()
{
List<Employee> list = db.Employees.ToList();
return Ok(list);
}
[System.Web.Http.HttpGet]
public IHttpActionResult GetEmployeeById(int id)
{
var emp = db.Employees.Where(model => model.id == id).FirstOrDefault();
return Ok(emp);
}
[System.Web.Http.HttpPost]
public IHttpActionResult EmpInsert(Employee e)
{
db.Employees.Add(e);
db.SaveChanges();
return Ok();
}
[System.Web.Http.HttpPut]
public IHttpActionResult EmpUpdate(Employee e)
{
db.Entry(e).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
//var emp = db.Employees.Where(model => model.id == e.id).FirstOrDefault();
//if(emp != null)
//{
// emp.id = e.id;
// emp.name = e.name;
// emp.gender = e.gender;
// emp.age = e.age;
// emp.designation = e.designation;
// emp.salary = e.salary;
// db.SaveChanges();
//}
//else
//{
// return NotFound();
//}
return Ok();
}
[System.Web.Http.HttpDelete]
public IHttpActionResult EmpDelete(int id)
{
var emp = db.Employees.Where(model => model.id == id).FirstOrDefault();
db.Entry(emp).State = System.Data.Entity.EntityState.Deleted;
db.SaveChanges();
return Ok();
}
}
}
Source Code – CrudMvcController – MVC Controller Code
using AspWebApi_Crud.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Mvc;
namespace AspWebApi_Crud.Controllers
{
public class CrudMvcController : Controller
{
// GET: CrudMvc
HttpClient client = new HttpClient();
public ActionResult Index()
{
List<Employee> emp_list = new List<Employee>();
client.BaseAddress = new Uri("http://localhost:1516/api/CrudApi");
var response = client.GetAsync("CrudApi");
response.Wait();
var test = response.Result;
if(test.IsSuccessStatusCode)
{
var display = test.Content.ReadAsAsync<List<Employee>>();
display.Wait();
emp_list = display.Result;
}
return View(emp_list);
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Employee emp)
{
client.BaseAddress = new Uri("http://localhost:1516/api/CrudApi");
var response = client.PostAsJsonAsync<Employee>("CrudApi", emp);
response.Wait();
var test = response.Result;
if (test.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
return View("Create");
}
public ActionResult Details(int id)
{
Employee e = null;
client.BaseAddress = new Uri("http://localhost:1516/api/CrudApi");
var response = client.GetAsync("CrudApi?id="+ id.ToString());
response.Wait();
var test = response.Result;
if (test.IsSuccessStatusCode)
{
var display = test.Content.ReadAsAsync<Employee>();
display.Wait();
e = display.Result;
}
return View(e);
}
public ActionResult Edit(int id)
{
Employee e = null;
client.BaseAddress = new Uri("http://localhost:1516/api/CrudApi");
var response = client.GetAsync("CrudApi?id=" + id.ToString());
response.Wait();
var test = response.Result;
if (test.IsSuccessStatusCode)
{
var display = test.Content.ReadAsAsync<Employee>();
display.Wait();
e = display.Result;
}
return View(e);
}
[HttpPost]
public ActionResult Edit(Employee e)
{
client.BaseAddress = new Uri("http://localhost:1516/api/CrudApi");
var response = client.PutAsJsonAsync<Employee>("CrudApi", e);
response.Wait();
var test = response.Result;
if (test.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
return View("Edit");
}
public ActionResult Delete(int id)
{
Employee e = null;
client.BaseAddress = new Uri("http://localhost:1516/api/CrudApi");
var response = client.GetAsync("CrudApi?id=" + id.ToString());
response.Wait();
var test = response.Result;
if (test.IsSuccessStatusCode)
{
var display = test.Content.ReadAsAsync<Employee>();
display.Wait();
e = display.Result;
}
return View(e);
}
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
client.BaseAddress = new Uri("http://localhost:1516/api/CrudApi");
var response = client.DeleteAsync("CrudApi/" + id.ToString() );
response.Wait();
var test = response.Result;
if (test.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
return View("Delete");
}
}
}
RouteConfig.cs Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace AspWebApi_Crud
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "CrudMvc", action = "Index", id = UrlParameter.Optional }
);
}
}
}
WebApiConfig.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace AspWebApi_Crud
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
Employee Model Class – Source Code
//------------------------------------------------------------------------------
// <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 AspWebApi_Crud.Models
{
using System;
using System.Collections.Generic;
public partial class Employee
{
public int id { get; set; }
public string name { get; set; }
public string gender { get; set; }
public int age { get; set; }
public string designation { get; set; }
public int salary { get; set; }
}
}
DbContext Class (web_api_crud_dbEntities) Source Code
//------------------------------------------------------------------------------
// <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 AspWebApi_Crud.Models
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class web_api_crud_dbEntities : DbContext
{
public web_api_crud_dbEntities()
: base("name=web_api_crud_dbEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Employee> Employees { get; set; }
}
}
Index.cshtml View Source Code
@model IEnumerable<AspWebApi_Crud.Models.Employee>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.id)
</th>
<th>
@Html.DisplayNameFor(model => model.name)
</th>
<th>
@Html.DisplayNameFor(model => model.gender)
</th>
<th>
@Html.DisplayNameFor(model => model.age)
</th>
<th>
@Html.DisplayNameFor(model => model.designation)
</th>
<th>
@Html.DisplayNameFor(model => model.salary)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.id)
</td>
<td>
@Html.DisplayFor(modelItem => item.name)
</td>
<td>
@Html.DisplayFor(modelItem => item.gender)
</td>
<td>
@Html.DisplayFor(modelItem => item.age)
</td>
<td>
@Html.DisplayFor(modelItem => item.designation)
</td>
<td>
@Html.DisplayFor(modelItem => item.salary)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.id }) |
@Html.ActionLink("Details", "Details", new { id=item.id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.id })
</td>
</tr>
}
</table>
Create.cshtml View Source Code
@model AspWebApi_Crud.Models.Employee
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Employee</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.gender, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.gender, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.gender, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.age, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.age, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.age, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.designation, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.designation, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.designation, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.salary, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.salary, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.salary, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
Details.cshtml View Source Code
@model AspWebApi_Crud.Models.Employee
@{
ViewBag.Title = "Details";
}
<h2>Details</h2>
<div>
<h4>Employee</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.name)
</dt>
<dd>
@Html.DisplayFor(model => model.name)
</dd>
<dt>
@Html.DisplayNameFor(model => model.gender)
</dt>
<dd>
@Html.DisplayFor(model => model.gender)
</dd>
<dt>
@Html.DisplayNameFor(model => model.age)
</dt>
<dd>
@Html.DisplayFor(model => model.age)
</dd>
<dt>
@Html.DisplayNameFor(model => model.designation)
</dt>
<dd>
@Html.DisplayFor(model => model.designation)
</dd>
<dt>
@Html.DisplayNameFor(model => model.salary)
</dt>
<dd>
@Html.DisplayFor(model => model.salary)
</dd>
</dl>
</div>
<p>
@Html.ActionLink("Edit", "Edit", new { id = Model.id }) |
@Html.ActionLink("Back to List", "Index")
</p>
Edit.cshtml View Source Code
@model AspWebApi_Crud.Models.Employee
@{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Employee</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.id)
<div class="form-group">
@Html.LabelFor(model => model.name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.gender, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.gender, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.gender, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.age, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.age, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.age, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.designation, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.designation, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.designation, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.salary, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.salary, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.salary, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
Delete.cshtml View Source Code
@model AspWebApi_Crud.Models.Employee
@{
ViewBag.Title = "Delete";
}
<h2>Delete</h2>
<h3>Are you sure you want to delete this?</h3>
<div>
<h4>Employee</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.name)
</dt>
<dd>
@Html.DisplayFor(model => model.name)
</dd>
<dt>
@Html.DisplayNameFor(model => model.gender)
</dt>
<dd>
@Html.DisplayFor(model => model.gender)
</dd>
<dt>
@Html.DisplayNameFor(model => model.age)
</dt>
<dd>
@Html.DisplayFor(model => model.age)
</dd>
<dt>
@Html.DisplayNameFor(model => model.designation)
</dt>
<dd>
@Html.DisplayFor(model => model.designation)
</dd>
<dt>
@Html.DisplayNameFor(model => model.salary)
</dt>
<dd>
@Html.DisplayFor(model => model.salary)
</dd>
</dl>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
<div class="form-actions no-color">
<input type="submit" value="Delete" class="btn btn-default" /> |
@Html.ActionLink("Back to List", "Index")
</div>
}
</div>
Click Below Link to Download Notes Of This Blog
https://www.mediafire.com/file/n79pq1s14mycv09/WEB+API+CRUD.pptx/file
Click Below Link to Download Source Code Of This Blog
https://www.mediafire.com/file/u5bytp760izhitp/AspWebApi_Crud.rar/file
No responses yet