please, I need help, why does [FromBody] fetch value always return null value. I have tried everything but nothing has worked, maybe you have a better idea? Please help, i stuck with this code
This is my javascript :
const DetailSewa = barangSewa;
const sewa = {
NotaSewa: $("#notaSewa").val(),
PelangganId: $("#cboSearchPelanggan").val(),
TempatAcara: $("#txtTempatAcara").val(),
TanggalAcara: $("#txtTanggalAcara").val(),
OngkosKerja: $("#ongkosKerja").val(),
OngkosKirim: $("#ongkosKirim").val(),
OngkosCuci: $("#ongkosCuci").val(),
SisaBayar: $("#sisaBayar").val(),
UangMuka: $("#uangMuka").val(),
TotalBayar: $("#totalBayar").val(),
TipeDokumen: $("#cboSearchDokumen").val(),
DetailSewa: DetailSewa,
};
$("#btnSimpan").closest("div.card-body").LoadingOverlay("show");
fetch("/Transaksi/CreateSewaPeralatan", {
method: "POST",
headers: { "Content-Type": "application/json;charset=utf-8" },
body: JSON.stringify(sewa),
})
.then((response) => {
$("#btnSimpan").closest("div.card-body").LoadingOverlay("hide");
return response.ok ? response.json() : Promise.reject(response);
})
.then((responseJson) => {
if (responseJson.State) {
swal("Terdaftar !", "Nota : " + $("#notaSewa").val(), "sukses");
} else {
swal("Maaf", "Sewa barang gagal terdaftar", "error");
}
})
.catch((error) => {
$("#btnSimpan").closest("div.card-body").LoadingOverlay("hide");
});
my controller :
[HttpPost]
public IActionResult CreateSewaPeralatan([FromBody] Sewa model)
{
ResponseSewa<Sewa> gResponse = new ResponseSewa<Sewa>();
try
{
_transaksiService.CreateSewa(model);
gResponse.State = true;
gResponse.Object = model;
}
catch (Exception ex)
{
gResponse.State = false;
gResponse.Message = ex.Message;
}
return StatusCode(StatusCodes.Status200OK, gResponse);
}
my config Json Serializtion:
services
.AddMvc()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
options.JsonSerializerOptions.PropertyNamingPolicy = null;
});
I hope the fetch can pass the value into controller
Why does [FromBody] fetch value always return null value. I have
tried everything but nothing has worked, maybe you have a better idea?
Please help, i stuck with this code.
Well, I have reeproduced your issue. You are getting null value on your controller because of your options.JsonSerializerOptions.PropertyNamingPolicy I am not sure why you have intented to set it as null. Either you should set to JsonNamingPolicy.CamelCase if you want to restrict CamelCase or just get rid of that.
Set to null means if anything doesn't matched it will always be empty. Thus, you are getting null value within your controller. You could modify as following:
Program.cs:
builder.Services.AddControllersWithViews().AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
})
Note: If you don't want to set JsonNamingPolicy.CamelCase just ommit or comment the full line.
Sample Model:
public class Sewa
{
public string NotaSewa { get; set; }
public int PelangganId { get; set; }
public string TempatAcara { get; set; }
}
Controller:
[HttpPost]
public IActionResult CreateSewaPeralatan([FromBody] Sewa model)
{
return StatusCode(StatusCodes.Status200OK);
}
Javascript:
const sewa = {
NotaSewa: "NotaSewa Value From Client Side",
PelangganId: 101,
TempatAcara: "TempatAcara",
};
console.log(sewa);
fetch("http://localhost:5094/JavascriptPost/CreateSewaPeralatan", {
method: "POST",
headers: { "Content-Type": "application/json;charset=utf-8" },
body: JSON.stringify(sewa),
});
Output:
Note: If you would like to know more details on JSON property naming policy you could check our official document here
Related
I'm trying to update a property in my database called "Estado". I'm using ajax to do it, like so:
function atualizaBD(idmarcador, novoEstado) {
$.ajax
({
url: `/api/IgnicoesAPI/${idmarcador}`,
type: 'PUT',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: JSON.stringify({ Id: idmarcador, Estado: novoEstado }),
async: true,
processData: false,
cache: false,
success: function (result) {
connection.invoke("PostMarker").catch(function (err) {
return console.error(err.toString());
});
},
error: function () {
alert("ocorreu um erro!")
}
});
}
Here is my model:
public class Ignicoes
{
public Ignicoes()
{
ListaOcorrencias = new HashSet<Ocorrencias>();
}
[Key]
public int Id { get; set; }
[Required]
public string Latitude { get; set; }
[Required]
public string Longitude { get; set; }
//estado(recusada, aceite, em avaliacao, concluido)
//public string Estado { get; set; }
[Required]
public string Estado { get; set; }
public DateTime DataInicioPropostaIgnicao { get; set; }
public DateTime DataDecisaoIgnicao { get; set; }
//lista de ocorrencias
public virtual ICollection<Ocorrencias> ListaOcorrencias { get; set; }
}
Here is my PUT method:
public async Task<IActionResult> PutIgnicoes([FromRoute] int id, [FromBody] Ignicoes ignicao)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != ignicao.Id)
{
return BadRequest();
}
else
{
var dataDecisao = DateTime.Now;
var ig = _context.Ignicoes.FirstOrDefault(ignicaoId => ignicaoId.Id.Equals(id));
if (ig != null)
{
ig.Estado = ignicao.Estado;
//ig.Estado = 0;
//ig.Latitude = ignicao.Latitude;
//ig.Longitude = ignicao.Longitude;
ig.DataDecisaoIgnicao = dataDecisao;
}
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!IgnicoesExists(id))
{
return NotFound();
}
else
{
throw;
}
}
}
return NoContent();
}
I already tried to use this code, but instead of changing the property "Estado" I changed the property "Latitude" and it worked perfectly. I don't know why this is happening. Both "Latitude" and "Estado" are the same type - String. Can somebody see the error?
Here is what appears in my output tab:
Here is the Network Analysis:
{"errors":{"Latitude":["The Latitude field is required."],"Longitude":["The Longitude field is required."]},"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"|43114da6-4594b09a6260f1a2."}
It would be easier to undestand the problem if you had added ajax http request + response logs as well (status and payloads). However, application output says 400 bad request for your API method ivocation.
Based on your resource class you have three properties declared as [Required] (except Id) : Longitude, Latitude, Estado, but in your ajax call you are passing only ID and Estado. More likely (if you are using asp.net validation) you have 400 response because of missing required properties in your ajax request body. Try to add missing properties data: JSON.stringify({ Id: idmarcador, Estado: novoEstado, string: latitude, string: longitude })
I'm trying to pass 3 parameters (2 types and one string),
but on the server side the parameters are null
this is my service
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json '
})
};
let body = {
auditId: auditId,
rolId: this.permisoService.currentUserRolValue.rolId,
valores: JSON.stringify(valores),
}
return this.http.post<any>(this._saveURL, body, httpOptions).pipe(
map(res => { return res; }),
catchError(this.handleError)
);
}
and the service side
[HttpPost, Route("AuditMail/Save"), Produces("application/json")]
public async Task<IActionResult> Save([FromBody] int auditId, int rolId , String valores)
{
return Json(await _repository.Save(auditId, rolId, valores));
}
i try to change the content-type to text/plain, remove [FromBody] with the same result,
I will appreciate any help thank you
See this answer to a similar question: https://stackoverflow.com/a/49082613/12431728 which says:
You can not get primitive types from your body directly like [FromBody] string id if your route content type is application/json because mvc waits model to bind json body to model not primitive types.
I would recommend creating a new class in your API project that holds these values:
public class AuditMailModel
{
public int AuditId { get; set; }
public int RolId { get; set; }
public string Valores { get; set; }
}
Then in your controller:
public async Task<IActionResult> Save([FromBody] AuditMailModel model)
{
return Json(await _repository.Save(model.AuditId, model.RolId, model.Valores));
}
This used to be a 415 error question.
Now it is a a receiving null values on the server side question.
I am having difficulty trying to get my values in the object myMessage over to the server side.
I have so far tried to add JSON.stringify to newMessage which is being console.logged in the service file.
I tried many ways to alter or make the object the way it would be recognized such as JSON.stringify() and creating a url ending with the correct parameters.
Sorry if it seems like I am dumping code below, but I have been working on this for a second day and don't understand why I can't do a simple post request with three parameters. One string, one int, and one datetime.
If anyone can see where I have gone wrong I would so appreciate it. I will be desperately waiting.
Below I am trying to hit api/SlgCorpNotes/Edit in backend from updateMessage(message: any) in the service in service.ts
slg-corp-notes.service.ts
import { Component, Injectable, Inject } from '#angular/core';
import { HttpClient, HttpHeaders, HttpResponse } from '#angular/common/http';
import { Observable, Subject, BehaviorSubject } from 'rxjs';
import { SLGReportParams, CorpNotes } from './models/slg.model';
import { SlgOverviewComponent } from './slg-overview/slg-overview.component';
import { SlgNote } from './models/slg-notes';
#Injectable({
providedIn: 'root'
})
export class SlgCorpNotesService {
constructor(private http: HttpClient, #Inject('BASE_URL') private baseUrl: string) { }
getWeekTempValue(endDate, department) {
var Params = '?endDate=' + endDate + '&department=' + department;
return this.http.get<any>(this.baseUrl + 'api/SlgCorpNotes/getWeekTempValue' + Params);
}
updateMessage(message: any) {
console.log("at service")
console.log(message)
var newMessage = new CorpNotes(message['departments'], message['noteBody'], message['weeks'].weekEnding)
var Params = '?Department=' + message['departments'] + '&Note=' + message['noteBody'] + '&WeekEnding=' + message['weeks'].weekEnding
console.log(newMessage)
console.log(JSON.stringify(newMessage))
console.log(Params)
const headers = new HttpHeaders()
.set('Content-Type', 'application/json;charset=UTF-8')
let options = { headers: headers };
return this.http.post(this.baseUrl + 'api/SlgCorpNotes/Edit', JSON.stringify(newMessage), options).subscribe(res => {
console.log(res);
}, error => {
console.log(error);
});;
}
}
model.ts
export class CorpNotes {
constructor(
public department: number,
public note: string,
public weekEnding: Date
) { }
}
SLGCorpNotesController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using mocHub2.Models;
using mocHub2.Models.Enterprise;
using Microsoft.EntityFrameworkCore;
using System.Data.SqlClient;
namespace mocHub2.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class SlgCorpNotesController : Controller
{
SLGContext _SLGContext;
BRDataContext _BRDataContext;
//injects new context
public SlgCorpNotesController(SLGContext context, BRDataContext context2)
{
_SLGContext = context;
_BRDataContext = context2;
}
// GET: api/SlgCorpNotes
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET: api/SlgCorpNotes/5
[HttpGet("{id}", Name = "Get")]
public string Get(int id)
{
return "value";
}
// POST: api/SlgCorpNotes
[HttpPost]
public void Post([FromBody] string value)
{
}
// Get Corporate Notes
[HttpGet("[action]")]
public JsonResult getWeekTempValue(DateTime endDate, int department)
{
// Find the WeekID from the weekending from SLGHeaderTemplate table
var WeekID = (from x in _SLGContext.SlgheaderTemplate
where x.WeekEnding == endDate
select x.Id).ToList();
// Find Department name by ID
var DepartmentString = (from x in _BRDataContext.Departments
where x.Department == department
select x.Description).ToList();
// Get the Note.
var DeptNote = from x in _SLGContext.SLGCorpNotes
where x.Department == DepartmentString[0]
&& x.WeekID == WeekID[0]
select x.Notes;
// Create return object
var notes = new Notes();
// If Note exists then return Json containing note and department for display, else return empty string.
if (DeptNote.Any() && WeekID.Count() > 0 && DepartmentString.Count() > 0)
{
var ReturnDeptNote = DeptNote.First();
notes = new Notes() { WeekID = WeekID[0], Department = DepartmentString[0], Note = ReturnDeptNote };
}
else
{
var ReturnDeptNote = "";
notes = new Notes() { WeekID = WeekID[0], Department = DepartmentString[0], Note = ReturnDeptNote };
}
return Json(notes);
}
[HttpPost]
[Route("Edit")]
public void Edit([FromForm] CorpNotes item)
{
_SLGContext.Entry(item).State = EntityState.Modified;
_SLGContext.SaveChanges();
}
}
public class CorpNotes
{
public int department { get; set; }
public string note { get; set; }
public DateTime weekEnding { get; set; }
}
public class Notes
{
public int ID { get; set; }
public int WeekID { get; set; }
public string Department { get; set; }
public string Note { get; set; }
}
}
Results of console.logs in the service file.
at service
slg-corp-notes.service.ts:22 {departments: 2, weeks: SLGTime, noteBody: "asdf"}
slg-corp-notes.service.ts:25 CorpNotes {department: 2, note: "asdf", weekEnding: "2019-11-02T00:00:00"}
slg-corp-notes.service.ts:26 {"department":2,"note":"asdf","weekEnding":"2019-11-02T00:00:00"}
slg-corp-notes.service.ts:27 ?Department=2&Note=asdf&WeekEnding=2019-11-02T00:00:00
slg-corp-notes.service.ts:28 Observable {_isScalar: false, source: Observable, operator: MapOperator}
app.module.ts
This is in my app.module.ts where I specify routes
{ path: 'slg-corp-notes', component: SlgCorpNotesComponent },
{ path: 'slg-corp-notes/edit/', component: SlgCorpNotesComponent }
slg-corp-notes.component.ts
save() {
console.log("at save")
if (!this.optionsForm.valid) {
return;
}
//this.Notes.note = this.optionsForm.get['noteBody'].value;
console.log(this.Notes);
this._slgCorpNotesService.updateMessage(this.optionsForm.value)
.subscribe((data) => {
this._router.navigate(['/slg-corp-notes']); //This will navigate back to the mochhub2 index where the message will be displayed
}, error => this.errorMessage = error)
}
Please let me know if additional info is needed.
1) You need to set the Content-Type header to application/json.
2) stringify the message.
const headers = new HttpHeaders()
.set('Content-Type', 'application/json;charset=UTF-8')
let options = { headers : headers };
this.http.post(this.baseUrl + 'api/SlgCorpNotes/Edit', JSON.stringify(newMessage), options);
At your angular side update your method like this
updateMessage(message: any) {
console.log("at service")
console.log(message)
var newMessage = new CorpNotes(message['departments'], message['noteBody'], message['weeks'].weekEnding)
var Params = '?Department=' + message['departments'] + '&Note=' + message['noteBody'] + '&WeekEnding=' + message['weeks'].weekEnding
console.log(newMessage)
console.log(JSON.stringify(newMessage))
console.log(Params)
var item = {
"Departments": message["Departments"],
"Note": message["noteBody"],
"WeekEnding": message["weeks"]
}
return this.http.post(this.baseUrl + 'api/SlgCorpNotes/Edit', item).subscribe(res
=> {
console.log(res);
}, error => {
console.log(error);
});
}
My problem is that when I send a complete Javascript object to my Web API Controller I always get null values. Even though I have a complete object I need to specify each attribute and value as you can see below. How can I make Web API accept a ready made Javascript object and bind it correctly?
C# Web Api Controller:
[Route("addcredentials/{salesId}")]
[HttpPost]
public IHttpActionResult AddCredentials([FromUri] int salesId, [FromBody] ScriveCredentials credentials)
{
return Ok(credentials);
}
C# Credentials object:
public class Credentials
{
public string ClientIdentifier { get; set; }
public string ClientSecret { get; set; }
public string TokenIdentifier { get; set; }
public string TokenSecret { get; set; }
}
Javascript object passed to resource, saved as "result" further down:
{ClientIdentifier: "a", ClientSecret: "b", TokenIdentifier: "c", TokenSecret: "d"}
Resource method:
addCredentials: {
method: 'POST',
url: 'api/addcredentials/:userSalesId'
}
Usage that results in null values:
userResource.addCredentials({ userSalesId: user.SalesId }, { credentials: result}).$promise.then(function (data) {
console.log(data);
});
Payload for this request:
{"credentials":{"ClientIdentifier":"a","ClientSecret":"b","TokenIdentifier":"c","TokenSecret":"d"}}
Usage that works but seems overly complicated:
userResource.addCredentials({ userSalesId: user.SalesId }, { ClientIdentifier: result.ClientIdentifier, ClientSecret: result.ClientSecret, TokenIdentifier: result.TokenIdentifier, TokenSecret: result.TokenSecret }).$promise.then(function (data) {
console.log(data);
});
Request payload:
{"ClientIdentifier":"a","ClientSecret":"b","TokenIdentifier":"c","TokenSecret":"d"}
Update
Tried the following and it did not work either, null on all values:
addScriveCredentials: {
method: 'POST',
url: 'api/addcredentials/'
result.SalesId = user.SalesId;
userResource.addCredentials({}, { credentials: result }).$promise.then(function (data) {
console.log(data);
});
C#:
[Route("addcredentials")]
[HttpPost]
public IHttpActionResult Addcredentials(Credentials credentials)
{
return Ok(credentials);
}
I had done a sample earlier, hope the follwing code will help you to understand.
The Model.
using System.ComponentModel.DataAnnotations;
public class ProductModel
{
public ProductModel(int id, string name, string category, decimal price)
{
Id = id;
Name = name;
Category = category;
Price = price;
}
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Category { get; set; }
[Required]
public decimal Price { get; set; }
}
The ApiController.
using Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Hosting;
using System.Web.Http;
public class ProductsController : ApiController
{
// other code omitted for brevity.
[HttpPost]
public IHttpActionResult PostProduct(ProductModel product)
{
try
{
if (product == null)
{
throw new ArgumentNullException("Product parameter cannot be null");
}
if (ModelState.IsValid)
{
// code omitted for brevity.
return this.Ok();
}
else
{
throw new Exception("Product is invalid");
}
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
[HttpPut]
public IHttpActionResult PutProduct(ProductModel product)
{
try
{
if (product == null)
{
throw new ArgumentNullException("Product parameter cannot be null");
}
if (ModelState.IsValid && product.Id > 0)
{
// code omitted for brevity.
return this.Ok();
}
else
{
throw new Exception("Product is invalid");
}
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
// other code omitted for brevity.
}
The Angular service.
// products.js
(function () {
"use strict";
angular
.module("exampleApp")
.constant("baseUrl", "http://localhost:53631/api/products/")
.factory("productsResource", productsResource);
productsResource.$inject = ["$resource", "baseUrl"];
function productsResource($resource, baseUrl) {
return $resource(baseUrl + ":id",
{
id: "#id"
},
{
create: {
method: "POST"
},
save: {
method: "PUT"
}
});
}
})();
The Angular controller. Focus on createProduct and updateProduct functions below
// edit.controller.js
(function () {
"use strict";
angular
.module("exampleApp")
.controller("EditController", EditController);
EditController.$inject = ["$routeParams", "$location", "productsResource"];
function EditController($routeParams, $location, productsResource) {
var vm = this;
vm.currentProduct = null;
vm.createProduct = createProduct;
vm.updateProduct = updateProduct;
vm.saveEdit = saveEdit;
vm.cancelEdit = cancelEdit;
if ($location.path().indexOf("/edit/") === 0) {
var id = $routeParams.id;
productsResource.get({ id: id }, function (data) {
vm.currentProduct = data;
});
}
function cancelEdit() {
$location.path("/list");
}
function updateProduct(product) {
product.$save().then(function () {
$location.path("/list");
});
}
function saveEdit(product) {
if (angular.isDefined(product.id)) {
vm.updateProduct(product);
} else {
vm.createProduct(product);
}
vm.currentProduct = {};
}
function createProduct(product) {
new productsResource(product).$create().then(function (newProduct) {
$location.path("/list");
});
}
}
})();
You could pass one object as the body of the post message instead.
Add a class like this
public class addCredentialObj
{
public int salesId { get; set; }
public Credentials credentials { get; set; }
}
Modify your controller like this (The use of FromBody can be read here)
[Route("addcredentials")]
[HttpPost]
public IHttpActionResult AddCredentials([FromBody]addCredentialObj obj)
{
return Ok(credentials);
}
In the client you need to create a matching json object to the addCredentialObj class
var yourCredentials = {"ClientIdentifier":"a","ClientSecret":"b","TokenIdentifier":"c","TokenSecret":"d"};
var jsonData = {
salesId: yourId,
credentials: yourCredentials
};
And then in the $http request to the controller, stringify the json object
$http({
method: 'POST',
url: 'api/addcredentials',
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
},
data: JSON.stringify(jsonData),
});
Here’s a brief (as I can make it) description of my problem, along with all relevant code. I'm hoping the wording for this post will be a bit clearer than my previous request for assistance.
I have a .NET Web API, and an AngularJS front end. I have a very simple POST method which accepts a parameter of the ‘Envelope’ type, shown here:
public class Envelope {
public int listingId { get; set; }
public string Description { get; set; }
public override string ToString() {
return listingId.ToString() + "; " + Description;
}
}
The actual POST method on the API appears here:
[EnableCors(origins: "http://simpleapiearl.azurewebsites.net", headers: "*", methods: "*")]
public class EnvelopesController : ApiController {
// POST: api/Envelopes
public string Post(Envelope env) {
return "rval: " + env.ToString() + " (and my addition to env)";
}
}
My front-end AngularJS $http POST looks like this:
$scope.testPOST = function () {
var env = {
listingId:1234,
Description:"some desc"
};
$http({
method: 'POST',
url: 'http://simpleApiEarl.azurewebsites.net/api/envelopes',
data: JSON.stringify(env),
headers: {
'Content-Type': 'application/json'
}
}).
success(function (data, status, headers, config) {
$scope.postStatus = 'success: ' + data;
}).
error(function (data, status, headers, config) {
$scope.postStatus = 'error: ' + status;
});
}
Here are my issues (numbered for easier reference):
Using all the code as shown above, I get a “400 (Bad Request)” when I call “testPOST()” from my page. This sounds like a .NET Web API routing issue, but I can’t figure out what it is.
I can avoid the 400 (and in fact get a 200) if I change the ‘Content-Type’ header to ‘application/x-www-form-urlencoded’. HOWEVER, that results in the API seeing the ‘env’ parameter as NULL.
I tend to adorn my action method parameter with a ‘[FromBody]’ attribute, but doing so does not fix the problem of ‘env’ being NULL in my API action method.
I have created a simple plunk with my very simple HTML page used to call the API. It can be found here:
http://plnkr.co/edit/hY2OUeg9CRQ1QOz8MGU8?p=info
Thanks very much for any assistance you can provide.
'Content-Type': 'application/x-www-form-urlencoded'
This will work.
This is Controller:
public async Task<HttpResponseMessage> GetData(int pageNo, int pageSize)
{
HttpResponseMessage response = null;
int totalPage, totalRecord;
totalRecord = db.Employees.Count();
totalPage = (totalRecord / pageSize) + ((totalRecord % pageSize) > 0 ? 1 : 0);
var record = (from a in db.Employees
orderby a.id
select a).Skip((pageNo - 1) * pageSize).Take(pageSize).ToList();
DataWithPaging data = new DataWithPaging
{
PageNo = pageNo,
PageSize = pageSize,
TotalPage = totalPage,
TotalRecord = totalRecord,
EmployeeData = record
};
response = Request.CreateResponse(HttpStatusCode.OK, data);
return await Task.FromResult(response);
}
You should have a class named: DataWithPaging
public class DataWithPaging
{
public int PageNo { get; set; }
public int PageSize { get; set; }
public int TotalPage { get; set; }
public int TotalRecord { get; set; }
public List<Employee> Employees { get; set; }
}