I would like to perform CRUD Operations on WEB API in asp.net using AJAX JQuery.I am very new to web api
The Following Code can be used to hit a web api with a GET Request
var url1 = 'http://api.com/customer/1234';
$.ajax({
url: url1,
type: 'GET',
headers: {
'customHeader': 'Value',
'customHeader2': 'Value2'
},
success: function (data) {
alert('Success');
}
});
Related
I'm posting data to an ASP.NET Core MVC 2.1.2 page using this jQuery code:
function OnCountryChange() {
$.ajax({
url: "/OnCountryChange",
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
headers: {
"RequestVerificationToken": $('input[name = __RequestVerificationToken]').val()
},
data: JSON.stringify({
sCountryCode: "Test 123"
})
});
}
I am receiving the post in the controller with this method:
[HttpPost]
[ValidateAntiForgeryToken]
[Route("/OnCountryChange")]
public IActionResult OnCountryChange([FromBody] string sCountryCode)
{
logger.LogDebug($"Country code is: {sCountryCode ?? "null"}");
return Json(sCountryCode);
}
The output printed to the log is:
Country code is: null
The raw request body (viewed using Fiddler) looks like this:
{"sCountryCode":"Test 123"}
Why isn't the data being passed?
I am not familiar with C#,but in your question you have add
contentType: "application/json; charset=utf-8"
in your Ajax method which means the data parameter is json format,so you need to access as json object instead of access string directly.
Two ways to solve it:
a. Change your C# controller method to access like a json object
b. Send Ajax parameter without json,code similar to below:
function OnCountryChange() {
$.ajax({
url: "/OnCountryChange",
type: "POST",
datatype: "json",
headers: {
"RequestVerificationToken": $('input[name = __RequestVerificationToken]').val()
},
data: {sCountryCode: "Test 123"}
});
}
I have a ASP.Net web API with one post method. I'm calling the post method from angular js. It is not passing me the data to API POST method, All my properties of my requestData object is null. I'm not sure what is the mistake am doing here. Can anyone help me plz.
API Code
public void Post(RequestData data)
{
.....
}
public class RequestData
{
PropertyDetail propertyDetails;
ICollection<Model1> model1s;
ICollection<Model2> model2s;
ICollection<Model3> model3;
ICollection<Model4> model4;
}
Client Code
var requesData = new RequestData();
requesData.model0= $scope.model0;
requesData.model1s= $scope.models;
requesData.model2s= $scope.model2s;
requesData.model3s= $scope.model3s;
requesData.model4s= $scope.model4s;
$http({
method: 'POST',
url: window.apiUrl,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: requesData,
}).then(function (res) {
console.log('succes !', res.data);
window.alert("Successfully created");
}).catch(function (err) {
debugger;
console.log('error...', err);
});
Probably, your server side couldn't map your parameters correctly. Data type matching is important while post some parameters. You can change your client code like this:
...
contentType: "application/json; charset=utf-8",
data: JSON.stringify(requestData),
dataType:'json',
...
After doing as #Jaky71 says, you can learn how .net expects those objects by calling dummy methods with nulls or whatever you nees to mimic.
.net has a strict parser
You can use angular.toJson:
$http({
method: 'POST',
url: window.apiUrl,
headers: { 'Content-Type': 'application/json' },
data: angular.toJson(requesData),
}).then(function (res) {
console.log('succes !', res.data);
window.alert("Successfully created");
}).catch(function (err) {
debugger;
console.log('error...', err);
});
Also make sure that your properties match.
I have created web-api to provide service like pin-code, Bank IFSC Code and so on, from my website named as http://www.ajaxserver.com
My all api is hosted on my site and my all client access using my site.
web api code is
[Route("api/GetURLName/")]
[HttpGet]
public string GetURLName(HttpRequestMessage request)
{
return HttpContext.Current.Request.Url.AbsoluteUri ;
}
One of my client website name is http://www.clientwebsite.online
client is used jquery to retrieve info like below code.
$('#btnTestCore').click(function () {
$.ajax({
url: 'http://ajaxserver.com/api/GetURLName/',
dataType: 'json',
type: 'GET',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
},
error: function (data) {
alert('failed.');
}
});
});
Output comes:
"http://ajaxserver.com/api/GetURLName/".
Need Output:
"http://clientwebsite.online/api/GetURLName/"
You could append the output to your AJAX request:
$('#btnTestCore').click(function () {
var urlname = encodeURI("http://clientwebsite.online/api/GetURLName/")
$.ajax({
url: 'http://ajaxserver.com/api/GetURLName?urlname=' + urlname,
dataType: 'json',
type: 'GET',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
},
error: function (data) {
alert('failed.');
}
});
});
You will then, of course, have to read that querystring in your webAPI code
As far as the server of the ajax request knows; the "site" is itself, so http://www.ajaxserver.com. You could try to look at the referrer, but... that isn't reliable across all browsers and protocols.
So you have two choices:
have the client API tell you the calling site - note that it could trivially be spoofed by the client
do some non-trivial proxy (etc) configuration such that the ajax server's site responds on the client domain
Note that http://clientwebsite.online/api/GetURLName/ was not the actual URL and is not going to come from anywhere by itself.
First of all, I'm not using MVC but only it's routing and controller (in order to create RESTful API). I'm using c# web form
The problem that I have is posting list of object using AJAX post to my api controllers. I've read several examples and tried their example to no anvil =( one of the example that I tried is this:
Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax
and
MVC Send list through AJAX
the data that I get is null, even I tried adding traditional: true in AJAX, still has no luck.
Maybe someone can give me some insight. Here's my code:
javascript:
var data = { warehouseProduct: [] };
data.warehouseProduct.push({
PID: 2,
PIDN: 'ABC',
CName: 'Toy',
EName: 'AKE-14',
Qty: 4,
});
$.ajax({
url: "/api/warehouse/PostUpdateData",
type: "POST",
contentType: 'application/json; charset=utf-8',
async: false,
dataType: "json",
traditional: true,
data: JSON.stringify(data),
error: function (xhr, ajaxOptions, thrownError)
{
alert(thrownError);
}
}).done(function (msg)
{
});
here's the code in the controller:
public string PostUpdateData(List<Warehouse> warehouseProduct)
{
// do something here
return "";
}
You wrapped the list of Warehouses in an object. You instead want to post just the array of Warehouses.
Try this:
var data = [];
data.push({
PID: 2,
PIDN: 'ABC',
CName: 'Toy',
EName: 'AKE-14',
Qty: 4,
});
I have created REST API in MVC4, it is working fine when I compose request from fiddler. But in my application, I need to call through jsonp because it would cross domain request. But when I'm calling this service it gives me error as shown below:
Jquery JsonP Call ..
$.ajax({
type: "POST" ,
url: "http://127.0.0.1:81/api/sites/GetDomainAvailability?apikey=asfasfdsf&callback=?",
data: { SubDomain: subDomain, ParentDomain: parentDomain, ResellerId: resellerId },
cache: false,
contentType: "application/json; charset=utf-8",
success: function (response) {
if (callback)
callback(response.d);
},
error: function (response) {
if (callback)
error(response.d);
},
});
Error:
Right now you are not doing JSONP. It's still POST request. To make it JSONP you need simply to add dataType: "jsonp" to you $.ajax() call. You can also remove some other redundancy parameters like content-type and 'callback' param (but that's optional). So, your code should looke like:
$.ajax({
url: "http://127.0.0.1:81/api/sites/GetDomainAvailability?apikey=asfasfdsf",
data: { SubDomain: subDomain, ParentDomain: parentDomain, ResellerId: resellerId },
datatype: "jsonp",
cache: false,
success: function (response) { /* ... */ },
error: function (response) { /* ... */ },
});
Be also ready, that your request will be transformed to a GET one and will look like
/GetDomainAvailability?apikey=key&callback=jquery123&SubDomain=sss&ParentDomain=ppp&ResellerId=123&_=4398572349857
So, prepare your server-side code for that.