(?)What we are doing?
We'll Create Simple WebApi and Calling using MVC Controller
So Lets See How to Do It.
Step-1:Create New Project
Step-2:Select Asp.Net Web Aplication and give proper Name.
Step-3:Select Template Web API
Step-4:Create one Model Class
Step-5:Click On Tool menu >NuGet Package Manager>Manage NuGet Package manager and install Entity FrameWork.
Step-6:Right Click on Model Folder From Solution Add one Class :(Employee)
Step-7:Add Following Code
--------------------------------------------------------------------------------------------------------------------------
using System;using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ApiDemo.Models
{
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public string City { get; set; }
}
}
--------------------------------------------------------------------------------------------------------------------------
Step-8:Create New Class Give Proper Name:(EmployeeContext)
--------------------------------------------------------------------------------------------------------------------------using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace ApiDemo.Models
{
public class EmployeeContext :DbContext
{
public EmployeeContext()
: base("EmployeeContext")
{
}
public DbSet<Employee> Employees { get; set; }
internal object find(int id)
{
throw new NotImplementedException();
}
}
}
Step-9:Create Connection String base on your Server,
=>open Webconfig file
=>and Write connection string
--------------------------------------------------------------------------------------------------------------------------
<connectionStrings>
<add name="EmployeeContext" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Dipti\Documents\EMPDB.mdf;Integrated Security=True;Connect Timeout=30" />
</connectionStrings>
--------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------
Step-10:Now Click on Tool menu Select NuGet Package Manager > Package Manager Console.
Step-11:Write In Bottom Of Window Following Code
-----------------------------------------------------------------------------------------------------------------------
enable-migrations
------------------------------------------------------------------------------------------------------------------------
Step-12:Now you can see the New folder (Migration) in our solution explorer,
Step-13:Open Migration Folder and open Configuration.cs change following code.
---------------------------------------------------------------------------------------------------------------------
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
//its always true
---------------------------------------------------------------------------------------------------------------------
Step-14:Write Simple Command in package manager console.
------------------------------------------------------------------------------------------------------------------------
update-database -force -verbose
------------------------------------------------------------------------------------------------------------------------
Step-15:your Database will be Created you can check it from database.
Step-16:In your Controller folder you have 2 controller 1.)ValueController 2).HomeController.
Step-17:Delete Value Controller.
Step-18:Now Add New folder in your Controller folder like..
Step-19:Add New Controller select web API2 Controller-empty.
Step-20: Now Create a New folder of "Api" And and drag your webapi controller(EmployeeController).
Step-21:Now Step by Step Follow this Code .
=>We Will insert data in table.
=>so in EmployeeController We'll Create method.
EmployeeController:
--------------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using ApiDemo.Models;
using System.Web.Http.Description;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
namespace ApiDemo.Controllers
{
[RoutePrefix("api/Employee")]
public class EmployeeController : ApiController
{
private object db;
public IHttpActionResult PostNewStudent(Employee employee)
{
if (!ModelState.IsValid)
return BadRequest("Not a valid model");
using (var ctx = new EmployeeContext())
{
ctx.Employees.Add(new Employee()
{
EmployeeId = employee.EmployeeId,
Name = employee.Name,
City = employee.City
});
ctx.SaveChanges();
}
return Ok();
}
-------------------------------------------------------------------------------------------------------------------------
Step-22:Same as you need to add code in our Home Controller
HomeController:
-------------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ApiDemo.Models;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace ApiDemo.Controllers
{
public class HomeController : Controller
{
HttpClient client;
string url = "http://localhost:1336/api/Employee";
public HomeController()
{
client = new HttpClient();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Employee employee)
{
//HTTP POST
var postTask = client.PostAsJsonAsync<Employee>("Employee", employee);
//postTask.Wait();
var result = postTask.Result;
if (result.IsSuccessStatusCode)
{
return RedirectToAction("index");
}
ModelState.AddModelError(string.Empty, "Server Error. Please contact administrator.");
return View(employee);
}
-------------------------------------------------------------------------------------------------------------------------
Step-23:Now You need to create "View" of create method
=>Right click in Create method and > Add View > and add .
=>Write following code.
Create.cshtml:
--------------------------------------------------------------------------------------------------------------------------
@model ApiDemo.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.City, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.City, "", 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>
}
-------------------------------------------------------------------------------------------------------------------------Step-24:Now you need to run your WebApi First time
.
=>because from that we will get url of api.
=>which we wrote in step-22[
string url = "http://localhost:1336/api/Employee";
]
=>For that run your web application.
=>in browser you can see:"localhost:1336"
=>you need to just write "/api/Employee" and press enter.
=>then you can copy your url .
=>and put it in our home controller .
Step-25:So Now our Webapi is ready to use
Now again run your application and write in URL:
=>in browser you can see:"localhost:1336"
"/Home/Create"
Step-26: Now you Can see the enter Name and city in textbox now click ok on button .
Step-27:You can check your database ,your data is inserted in data base.
==>now same things follow for display data,edit data ,details ,and delete
=>i have already implemented this code you can use it.
EmployeeController:
------------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using ApiDemo.Models;
using System.Web.Http.Description;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
namespace ApiDemo.Controllers
{
[RoutePrefix("api/Employee")]
public class EmployeeController : ApiController
{
private object db;
public IHttpActionResult PostNewStudent(Employee employee)
{
if (!ModelState.IsValid)
return BadRequest("Not a valid model");
using (var ctx = new EmployeeContext())
{
ctx.Employees.Add(new Employee()
{
EmployeeId = employee.EmployeeId,
Name = employee.Name,
City = employee.City
});
ctx.SaveChanges();
}
return Ok();
}
public IEnumerable<Employee> GetDetails()
{
EmployeeContext db = new EmployeeContext();
var emp = db.Employees.ToList();
return emp;
}
[Route("get/{id}")]
public IHttpActionResult Get(int id)
{
EmployeeContext db = new EmployeeContext();
var emp = db.Employees.FirstOrDefault(s => s.EmployeeId == id);
return Ok(emp);
}
[Route("put/")]
public IHttpActionResult Put(Employee employee)
{
using (var ctx = new EmployeeContext())
{
var existEmp= ctx.Employees.Where(s => s.EmployeeId == employee.EmployeeId)
.FirstOrDefault<Employee>();
if (existEmp != null)
{
existEmp.Name = employee.Name;
existEmp.City = employee.City;
ctx.SaveChanges();
}
else
{
return NotFound();
}
}
return Ok();
}
[Route("delete/{id}")]
public IHttpActionResult Delete(int id)
{
using (var ctx = new EmployeeContext())
{
var emp = ctx.Employees.Where(s => s.EmployeeId == id).FirstOrDefault();
ctx.Entry(emp).State = System.Data.Entity.EntityState.Deleted;
ctx.SaveChanges();
}
return Ok();
}
}
}
------------------------------------------------------------------------------------------------------------------------
HomeController:
------------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ApiDemo.Models;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace ApiDemo.Controllers
{
public class HomeController : Controller
{
HttpClient client;
string url = "http://localhost:1336/api/Employee";
public HomeController()
{
client = new HttpClient();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task<ActionResult> Index()
{
HttpResponseMessage responseMessage = await client.GetAsync(url);
if (responseMessage.IsSuccessStatusCode)
{
var responseData = responseMessage.Content.ReadAsStringAsync().Result;
var Employees = JsonConvert.DeserializeObject<List<Employee>>(responseData);
return View(Employees);
}
return View("Error");
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Employee employee)
{
//HTTP POST
var postTask = client.PostAsJsonAsync<Employee>("Employee", employee);
//postTask.Wait();
var result = postTask.Result;
if (result.IsSuccessStatusCode)
{
return RedirectToAction("index");
}
ModelState.AddModelError(string.Empty, "Server Error. Please contact administrator.");
return View(employee);
}
public ActionResult Edit(int id)
{
//Employee employee = null;
var response = client.GetAsync(url + "/get/" + id);
var result = response.Result;
if (result.IsSuccessStatusCode)
{
var read = result.Content.ReadAsStringAsync().Result;
var em = JsonConvert.DeserializeObject<Employee>(read);
return View(em);
}
return View();
}
[HttpPost]
public ActionResult Edit(Employee employee)
{
var put = client.PutAsJsonAsync(url + "/put", employee);
var result = put.Result;
if (result.IsSuccessStatusCode)
{
return RedirectToAction("index");
}
return View(employee);
}
public ActionResult Details(int id)
{
var response = client.GetAsync(url + "/get/" + id);
var result = response.Result;
if (result.IsSuccessStatusCode)
{
var read = result.Content.ReadAsStringAsync().Result;
var em = JsonConvert.DeserializeObject<Employee>(read);
return View(em);
}
return View();
}
public ActionResult Delete(int id)
{
var delete = client.DeleteAsync(url + "/Delete/" + id);
var result = delete.Result;
return RedirectToAction("index");
}
}
}
------------------------------------------------------------------------------------------------------------------------
step-28:You Have to add view of all method which is located in Home Controller
We have done create.cshtml,
=>same as following are helpfull for you :
Step-29:Index.cshtml(for list of details)
Index.cshtml:
-------------------------------------------------------------------------------------------------------------------------
@model IEnumerable<ApiDemo.Models.Employee>
@{
ViewBag.Title = "index";
}
<h2>index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.City)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.City)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.EmployeeId }) |
@Html.ActionLink("Details", "Details", new { id=item.EmployeeId }) |
@Html.ActionLink("Delete", "Delete", new { id=item.EmployeeId })
</td>
</tr>
}
</table>
-------------------------------------------------------------------------------------------------------------------------
Step-30:for Edit.cshtml
Edit.CShtml:
--------------------------------------------------------------------------------------------------------------------------
@model ApiDemo.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.EmployeeId)
<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.City, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.City, "", 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")
}
--------------------------------------------------------------------------------------------------------------------------
Step-31:for Details.cshtml
Details.CShtml:
--------------------------------------------------------------------------------------------------------------------------
@model ApiDemo.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.City)
</dt>
<dd>
@Html.DisplayFor(model => model.City)
</dd>
<div>
@Html.ActionLink("Back to List", "Index") |
</div>
</dl>
</div>
--------------------------------------------------------------------------------------------------------------------------
SO Finally You Can see:
-------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------
Now You can add ,remove,edit ,your details.
Now You can add ,remove,edit ,your details.
For more Details ask in comment.
Thank You








No comments:
Post a Comment