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.ModelBinding;
using System.Web.Http.OData;
using System.Web.Http.OData.Routing;
using Test.Models;
namespace Test.Controllers
{
/*
To add a route for this controller, merge these statements into the Register method of the WebApiConfig class. Note that OData URLs are case sensitive.
using System.Web.Http.OData.Builder;
using Test.Models;
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<EMP1>("Emp");
config.Routes.MapODataRoute("odata", "odata", builder.GetEdmModel());
*/
public class EmpController : ODataController
{
private TestEntities db = new TestEntities();
// GET odata/Emp
[Queryable]
public IQueryable<EMP1> GetEmp()
{
return db.EMP1;
}
// GET odata/Emp(5)
[Queryable]
public SingleResult<EMP1> GetEMP1([FromODataUri] int key)
{
return SingleResult.Create(db.EMP1.Where(emp1 => emp1.EID == key));
}
// PUT odata/Emp(5)
public IHttpActionResult Put([FromODataUri] int key, EMP1 emp1)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (key != emp1.EID)
{
return BadRequest();
}
db.Entry(emp1).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!EMP1Exists(key))
{
return NotFound();
}
else
{
throw;
}
}
return Updated(emp1);
}
// POST odata/Emp
public IHttpActionResult Post(EMP1 emp1)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.EMP1.Add(emp1);
try
{
db.SaveChanges();
}
catch (DbUpdateException)
{
if (EMP1Exists(emp1.EID))
{
return Conflict();
}
else
{
throw;
}
}
return Created(emp1);
}
// PATCH odata/Emp(5)
[AcceptVerbs("PATCH", "MERGE")]
public IHttpActionResult Patch([FromODataUri] int key, Delta<EMP1> patch)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
EMP1 emp1 = db.EMP1.Find(key);
if (emp1 == null)
{
return NotFound();
}
patch.Patch(emp1);
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!EMP1Exists(key))
{
return NotFound();
}
else
{
throw;
}
}
return Updated(emp1);
}
// DELETE odata/Emp(5)
public IHttpActionResult Delete([FromODataUri] int key)
{
EMP1 emp1 = db.EMP1.Find(key);
if (emp1 == null)
{
return NotFound();
}
db.EMP1.Remove(emp1);
db.SaveChanges();
return StatusCode(HttpStatusCode.NoContent);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool EMP1Exists(int key)
{
return db.EMP1.Count(e => e.EID == key) > 0;
}
}
}
WEBAPI confic code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.OData.Builder;
using Test.Models;
namespace Test
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<EMP1>("Emp");
config.Routes.MapODataRoute("odata", "odata", builder.GetEdmModel());
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
Wiew Code:
@{
Layout = null;
}
<body>
<div style="width:100%">
<div id="EmpContainer"></div>
</div>
</body>
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<link href="~/jtable/themes/lightcolor/gray/jtable.css" rel="stylesheet" />
<link href="~/jtable/themes/metro/lightgray/jtable.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery-ui-1.9.2.js"></script>
<script src="~/jtable/jquery.jtable.min.js"></script>
<script type="text/javascript">
$(function () {
$('#EmpContainer').jtable({
title: 'Employee Information',
paging: true,
pageSize: 5,
sorting: true,
multiSorting: true,
defaultSorting: 'EID asc',
actions: {
listAction: getListData,
deleteAction: deleteItem,
createAction: createItem,
updateAction: updateItem
},
fields: {
EID: {
title: 'EID',
width: '30%',
key: true,
create: true,
edit: false,
list: true
},
NAME: {
title: 'Name',
width: '50%'
}
}
});
$('#EmpContainer').jtable('load');
function getListData(postData, jtParams) {
var ret;
var query = "/odata/Emp" //root uri
+ "?$select=EID,NAME" //reduce the payload to what we need
+ "&$inlinecount=allpages"
+ "&$skip=" + jtParams.jtStartIndex
+ "&$top=" + jtParams.jtPageSize
+ "&$orderby=" + jtParams.jtSorting.replace(' DESC', ' desc').replace(' ASC', ' asc')
// + "&$format=json" //give me json... will be used in newer OData
//+ "&$callback=callback"; //this is my callback for future
return $.Deferred(function ($dfd) {
$.ajax({
url: query,
type: 'GET',
dataType: 'json',
data: postData,
success: function (data) {
ret = {
'Result': "OK",
'Records': data.value,
'TotalRecordCount': data['odata.count']
};
$dfd.resolve(ret);
},
error: function () {
$dfd.reject();
}
});
});
}
function createItem(postData) {
var ret;
return $.Deferred(function ($dfd) {
$.ajax({
url: '/odata/Emp',
type: 'POST',
dataType: 'json',
data: postData,
success: function (data) {
ret = {
'Result': "OK",
'Record': data
};
$dfd.resolve(ret);
},
error: function () {
$dfd.reject();
}
});
});
}
function updateItem(item) {
var ret;
return $.Deferred(function ($dfd) {
$.ajax({
url: '/odata/Emp(' + getParameterByName(item, 'EID') + ')',
type: 'PUT',
dataType: 'json',
data: item,
success: function (data) {
ret = {
'Result': "OK",
'Record': data
};
$dfd.resolve(ret);
},
error: function () {
$dfd.reject();
}
});
});
}
function getParameterByName(str, name) {
var sURLVariables = str.split('&');
for (var i = 0; i < sURLVariables.length; i++) {
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == name) {
return sParameterName[1];
}
}
}
function deleteItem(item) {
return $.Deferred(function ($dfd) {
$.ajax({
url: '/odata/Emp(' + item.EID + ')',
type: 'DELETE',
dataType: 'json',
data: item,
success: function (data) {
$dfd.resolve({ 'Result': "OK" });
},
error: function () {
$dfd.reject();
}
});
});
}
});
</script>
No comments:
Post a Comment