Pass string array as data in jquery ajax to web api - javascript

I am trying to pass string array to a Web Api method which accepts an array of strings as argument. Bellow my Web Api method
[HttpGet]
public string HireRocco(string[] hitList)
{
string updateList = string.Empty;
return updateList;
}
My ajax
var uri = 'http://localhost:16629/api/AssassinApi/HireRocco',
hitList = ['me', 'yourself'];
$.ajax({
url: uri,
type: 'GET',
data: { hitList : hitList },
cache: false,
dataType: 'json',
async: true,
contentType: false,
processData: false,
success: function (data) {
},
error: function (data) {
}
});
The above ajax successfully hits the HireRocco method but hitList param is still null. What should I change to pass an array of strings as param.

If you need to send data via a HttpGet, you can add [FromUri] you can edit your controller action as follows and your JavaScript should work as is:
[HttpGet]
public string HireRocco([FromUri] string[] hitList)
{
string updateList = string.Empty;
return updateList;
}

Remove contentType: false then set processData to true so it can append the postData your url, as that's how a get request works or you will have to change your api to accept POST request which are set through the header.
$.ajax({
url: uri,
type: 'GET',
data: { hitList : hitList },
cache: false,
dataType: 'json',
async: true,
processData: true,
success: function (data) {
console.log(data);
},
error: function (data) {
}
});

First of all i suggest that you use POST rather than GET.
create a javascript array. push the data inside it. send it to web api action method by using JSON.Stringify.. and then process the further logic.
In web api create a model variable.. and create a list object..
Following is the code..
Javascript
var demoarray=[];
demoarray.push({"test1":"hi", "test2":"hello"}); //test1 and test2 are model variable names in web api and hi and hello are their values
you can repeat the process in for loop or something for adding multiple values.
$.ajax({
url:"http://localhost..",
type: "POST",
data: JSON.Stringify(demoarray),
contentType: "application/json",
success: function(data)
{
},
error: function(data)
{
}
});
WEB API Code
Create a model class and two properties
public string test1 {get; set;}
public string test2 {get; set;}
controller code
[Httppost]
public void actionmethod(List<modelclass> obj)
{
int i=0;
for(i=0; i<obj.count; i++)
{
//your logic
}
}

Related

jQuery GET with parameters always null on server side

I don't know what I'm missing.
Everything works when passing complex custom objects, but when I try to pass a simple int or string I get null
Here is the ajax call on client side:
var id = 1;
$.ajax({
type: "GET",
url: "/api/APICalls/MethodName",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(id), // or JSON.stringify({id: id}) or just id
dataType: "json",
success: function (data) {
console.log(data);
},
error: function (data) {
alert(data.responseText);
}
});
On server side the method is as follows:
[HttpGet]
public void MethodName([FromBody] string id)
{
// Do something with id... Doesn't matter... It is `null`!
}
The reason why you are getting null value for id parameter is [FromBody]. Technically when you send GET request to the server with jQuery the data is presented in the query parameters and not in the request body.
What you need to do on backend side is just to remove [FromBody] as follows:
[HttpGet]
public void MethodName(string id)
{
// Now you should be able to access the value of id
}
Sending data from client side as the following:
var id = 1;
$.ajax({
url: '/api/APICalls/MethodName',
type: 'GET',
data: {id: id},
success: function (data) {
console.log(data);
},
error: function (err) {
console.error(err);
}
});
From the documentation for [FormBody] you can read the following:
To force Web API to read a simple type from the request body, add the [FromBody] attribute to the parameter.
Your data was presented in the query string, checking the network tab in Chrome:
I hope this helps!

How to pass array variable from view to controller in spring mvc

I want to pass the variable from view to controller I am using ajax call to achieve it i am getting the error below. I don't know what i am missing here.
WARN 41440 --- [nio-8080-exec-9] o.s.web.servlet.PageNotFound : Request method 'POST' not supported
This is my code
document.getElementById('btntest').onclick = function(){
var selchbox = getSelectedChbox(this.form); // gets the array returned by getSelectedChbox()
myvalue = JSON.stringify(selchbox);
//document.write("check check"+selchbox);
$.ajax({
type: "POST",
url: "UserController/delete",
contentType: "application/json; charset=utf-8",
data: {key:myvalue},
cache: false,
success: function (data) {
alert("Are you sure?");
},
error: function (args) {
alert("Error on ajax post");
}
});
alert(selchbox);
}
My controller method looks like below
#RequestMapping(value = "/delete", method = RequestMethod.POST)
public String delete(#RequestBody String key) {
System.out.println("My Array value"+key.toString());
return key;
}
What i am missing here? Any Help
Finally i could able to pass the values from my view to controller I am posting the code.
This is my js code
document.getElementById('btntest').onclick = function(){
var selchbox = getSelectedChbox(this.form); // gets the array returned by getSelectedChbox()
var myvalue = JSON.stringify(selchbox);
//document.write("check check"+selchbox);
$.ajax({
type: "POST",
url: "/delete",
dataType : "JSON",
contentType:"application/json; charset=utf-8",
data: JSON.stringify(selchbox),
cache: false,
success: function (data) {
alert("Are you sure?");
},
error: function (args) {
alert("Error on ajax post");
}
});
alert(selchbox);
}
And my controller code
#RequestMapping(value = "/delete", method = RequestMethod.POST)
public String delete(#RequestBody String value){
System.out.println("My Array value"+value.toString());
return value;
}
First, if you want to delete, why not use the verb delete http?
I think you are not using the correct parameter: RequestParam is used to map your sORGID parameter to the URL (a parameter you did not use on the client side, you must use it or delete it).
If you want to map Json, you must use #RequestBody.
I hope it helps
At leaset two problems
url: "UserController/delete" in your ajax won't match "/delete/{sORGID}" in your controller.
data: {key:myvalue} in your ajax, the property name is key, in your controller it's myvalue[], this should also be the same.

Error while calling Webapi in my asp.net project

This is my api code that return successfull json data while using get method
public Question[] Get() {
getQuestion obj = new AllDataAccess.getQuestion();
return obj.questionList().ToArray();
}
This is my post method data that accept the value and save in database
public void Post([FromBody] string question) {
SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
obj.savaData(question);
}
This is the method that call my api
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'http://localhost:53893/api/values',
data: "{'question':'" + $("#submit").value + "'}",
dataType: 'json',
async: false,
success: function(data, status) {
console.log(status);
},
error: function(err) {
console.log(err);
}
});
Now the problem is when i post the data with one textbox value its give me a message in console that "nocontent" and record save in data base with null value
It seems that your ajax url is wrong. You should specify the action name (post). Also, use JSON.stringify to retrieve proper json from javascript object.
var postData = { question:$("#submit").val() };
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'http://localhost:53893/api/values/post',
data: JSON.stringify(postData),
dataType: 'json',
success: function (data,status) {
console.log(status);
},
error: function (err) {
console.log(err);
}
});
In the server side, you should create a model class for Post method;
public class PostInput
{
public string Question { get; set; }
}
And then Post method looks like;
[HttpPost]
public void Post([FromBody]PostInput input)
{
SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
obj.savaData(question);
}
If you want to use FromBody, you can do so.
JavaScript
$.ajax({
type: "POST",
//default content-type, could be omitted
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
url: 'http://localhost:53893/api/values/post',
data: {'': $("#submit").val()}
});
API action
[HttpPost]
public void Post([FromBody]string question)
{
SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
obj.savaData(question);
}
You had these issues.
Wrong content-type for your ajax call.
Data was not posted correctly.
val() should be used instead of .value.
API action should be decorated with [HttpPost].

Model binding a list on a complex type in ASP.NET Core

I'm having trouble with model binding in ASP.NET Core MVC. I have this endpoint, which gets hit when called from Javascript, but the postData is always null.
[HttpPost("/somepost")]
public string SomePost([FromBody] PostData postData)
{
return "Got It!";
}
public class PostData
{
public int ID { get; set; }
public string[] ListOrArray { get; set; } // Doesn't matter if this ends up a List or an Array
}
This endpoint is being hit from a $.click function:
$('img.some-image').click(function () {
array = ['sample data', 'some more'];
data = {
ID: 1,
ListOrArray: array
};
$.ajax({
type: 'POST',
url: '/somepost',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: data,
success: function (result) {
console.log('Received: ');
console.log(result);
}
});
});
I'm guessing that the problem is model binding, but I am not sure. I've seen examples with lowercase Javascript object property names, but that didn't change anything for me.
I also have to remove [ValidateAntiForgeryToken] from the POST, but I would prefer adding it back in. I'm guessing that I would have to add the token to the GET request so that I could submit it for the POST, but I haven't figured out how to do that. I don't think that has anything to do with my problem though.
I've searched for answers and examples, but none of them have worked for me. ASP.NET Core is pretty new so there isn't much out there. I am on version 1.1.0.
You have set contentType:json but you are sending a plain object you need to send json object.
To convert your object to json object you can use JSON.stringify
$.ajax({
type: 'POST',
url: '/somepost',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
success: function (result) {
console.log('Received: ');
console.log(result);
}
});

Ajax query string not being posted to ASP.NET controller

I have this Ajax function:
UpdateFIConfig: function ($appForm) {
var valid = $appForm.valid();
//if not valid the validate plugin will take care of the errors
if (valid) {
$appForm.serialize();
$.ajax({
url: '/IdentifiConfig/DefaultConfiguration/UpdateFIConfig',
data: $appForm,
dataType: 'application/json',
cache: false,
type: 'POST',
success: function (data) {
if (data.Error) {
cc.jqUtils.openDialog(data.ErrorDescription, 'Error', 'OK', null, null, null);
} else {
window.location.href = '/IdentifiConfig/DefaultConfiguration';
}
}
});
}
},
Which serializes data sent from my view into a query string. I know the data is serialized correctly because I have viewed the string with console.log($appForm), and it's correct.
However, my controller never receives the query string. I have removed a lot of code, but this is basically what the controller function looks like:
[HttpPost]
public ActionResult UpdateFIConfig(string query)
{
NameValueCollection nvc = HttpUtility.ParseQueryString(query);
System.Diagnostics.Debug.WriteLine(nvc);
}
I receive a null pointer on the line which tries to parse the query string, and I don't know why. Any help?
i have the same thing ajax in my project the only different is i don't use dataType
but contentType: "application/json; charset=utf-8"
data: "{'query' : '" + $appForm + "'}"
This bit:
$appForm.serialize();
Returns a string that you're never using. serialize won't actually modify the form. You should assign it to a variable and pass that up instead:
var data = $appForm.serialize();
$.ajax({
url: '/IdentifiConfig/DefaultConfiguration/UpdateFIConfig',
data: data,
/* etc */
});
There is probably a better way, but I get around this annoyance by accepting an Object with a string property instead of just a string. So do something like:
[HttpPost]
public ActionResult UpdateFIConfig(MyTypeWithQry query)
{ ...
and
$.ajax({ url: '/IdentifiConfig/DefaultConfiguration/UpdateFIConfig',
data: { 'query' : $appForm },
dataType: 'application/json',
...

Categories

Resources