I created a odata web api using below link Microsoft Doc OData V4 Link
So my solution contains two project
- ODATAWebApi
- WebApp
Please find the code WebApp Code I am able to consume & post the data to odata web api by below code
index.html
<input type="text" id="txtName" value="" />
<br />
<input type="text" id="txtPrice" value="" />
<br />
<input type="text" id="txtCategory" value="" />
<br />
<input type="button" id="btnPostData" value="Post Data Via Query " />
<input type="button" id="btnPostData2" value="Post Data Via Json Object" />
Ajax Code
$("#btnPostData").bind("click", function () {
var Name = $("#txtName").val();
var Price = $("#txtPrice").val();
var Category = $("#txtCategory").val();
//I am creating a query string to post the data to odata web api
var PostData = "Name=" + Name + "&Price=" + Price + "&Category=" + Category;
$.ajax({
url: 'https://localhost:44340/api/Products',
type: 'POST',
crossDomain: true,
dataType: 'json',
data:PostData,
success: function (data) {
alert('Data: ' + data);
},
error: function (request, error) {
console.log("Request: " + JSON.stringify(request));
alert("Request: " + JSON.stringify(request));
}
});
});
Using the above methodology we were able to post the data to odata web api but i want to post the data via json object as shown below but it is not working
Product Model
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
}
Json Product Model
$("#btnPostData2").bind("click", function () {
var Product = {
Id : null,
Name: $("#txtName").val(),
Price: $("#txtPrice").val(),
Category: $("#txtCategory").val()
}
$.ajax({
url: 'https://localhost:44340/api/Products',
type: 'POST',
crossDomain: true,
dataType: 'json',
data: JSON.stringify(Product),
success: function (data) {
alert('Data: ' + data);
},
error: function (request, error) {
console.log("Request: " + JSON.stringify(request));
alert("Request: " + JSON.stringify(request));
}
});
});
Using above methodology I am not able to post the data to odata web api. please help or please let me known any other way to post the data to odata web api.