Ajax query string not being posted to ASP.NET controller - javascript

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',
...

Related

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.

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);
}
});

When sending jQuery post to MVC controller getting 404 error

I'm sending from view using jQuery to MVC post action
function DoSomething(passedId) {
$.ajax({
method: "POST",
dataType: 'text',
url: '/MyController/SomeAction/',
data: { id: passedId}
}).done(function (data) {
//
});
}
And inside MyController
[HttpPost]
public ActionResult SomeAction(int id)
{
...
}
In Firebug console I'm getting 404 error.
You didn't said which version of jquery you are using. Please check jquery version and in case that this version is < 1.9.0 you should instead of
method: "POST"
use
type: "POST"
this is an alias for method, and according to jquery official documentation you should use type if you're using versions of jQuery prior to 1.9.0.
function DoSomething(passedId) {
$.ajax({
type: "POST",
dataType: 'text',
url: '/MyController/SomeAction/',
data: { id: passedId}
}).done(function (data) {
...
});
}
Tested above code and it works (each request enter inside mvc controller http post SomeAction action).
In the RFC 2616 the code 404 indicates that the server has not found anything matching the Request-URI.
So you need to look at your URL parameter.
Try the MVC conventional call using :
url: '#Url.Action("SomeAction", "MyController")',
To resolve the 404 issue:
There are a few options to resolve this. You controller/action cannot be find the way it is describe.
-If you are in a view that is in the controller for which the action your are trying to call is located, then:
url: 'SomeAction',
-If you are trying to call an action from another controller, OtherController, for example, then:
url: 'Other/SomeAction',
-To add to another answer, if you are calling your ajax inside the view (and NOT in a javascript file) then you can also use (for a controller called SomeController):
url: '#Url.Action("SomeAction", "Some")',
Additional Items Of Note:
You do not specify a content type for json (contentType indicates what you are sending):
contentType: "application/json; charset=utf-8",
I can't tell, based on your action if you are expecting 'text' or something else. However, unless expecting 'json', I would remove the data part.
You need to stringify your data
JSON.stringify(data: { id: passedId}),
In the end, I would expect it to look something like:
function DoSomething(passedId) {
var url = "SomeAction"; //if action is in OtherController then: "Other/SomeAction"
$.ajax({
method: "POST",
url: url,
data: JSON.stringify({ id: passedId}),
contentType: "application/json; charset=utf-8"
}).done(function (data) {
//
});
}
The slash at the beginning of this designates an absolute path, not a relative one.
/MyController/SomeAction/
You should include a URL or relative path.. maybe
'MyController/SomeAction/ajax.php'
or the full URL
'http://example.com/myajaxcontroller/someaction/ajax.php'
or stolen from the other guys answer
url: '#Url.Action("SomeAction", "MyController")',
To address others on here, I don't think the datatype is the
problem... OP says "I'm getting 404 error."
contentType is the type of data you're sending, so
application/json; charset=utf-8 is a common one, as is
application/x-www-form-urlencoded; charset=UTF-8, which is the
default.
dataType is what you're expecting back from the server: json, html,
text, etc. jQuery will use this to figure out how to populate the success function's parameter.
Write the code this way:
function DoSomething(passedId) {
$.ajax({
url: 'yourController/SomeAction',
type: 'POST',
data: { id: passedId},
dataType: 'json',
error: function (ex) {alert(ex.responseText)},
success: function (data)
{
if (data.Results != null) {
//use the return values
});
}
}
});
}
and the controller
public JsonResult SomeAction(int id)
{
try
{
return Json(new { Results = "Text To return or send some object or an list, etc"}, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
throw;
}
}
Finally, check that the controller has its respective view. :)
and and the library of "jQuery" updated.
just in case.
use the following ajax call
var datum = { id: passedId };
$.ajax({
url: url, // your url
type: 'POST',
data: JSON.stringify(datum),
contentType: 'application/json; charset=utf-8',
beforeSend: function () {
},
complete: function () {
},
success: function (user, status, XHR) {
},
error: function (req, status, error) {
}
});
UpDated
public ActionResult SomeAction(int id){} should accept string parameter instead of int

Pass string array as data in jquery ajax to web api

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
}
}

Using $.ajax to POST XML to MVC Controller method

I have a simple controller function like this:
<HttpPost>
Function SaveXML(payload As String) As Boolean
If payload IsNot Nothing AndAlso payload.Length > 0 Then
Return True
Else
Return False
End If
End Function
Which I'm calling from JavaScript like this:
function SaveXML() {
var payload = '<?xml version="1.0" encoding="utf-8"?><data>XML_GOES_HERE</data>';
// Calls controller correctly but data is null
$.ajax({
url: "/Data/SaveXML/",
type: "POST",
processData: false,
contentType: "text/xml",
data: payload
})
.done(function () { alert('Application saved.'); })
.fail(function () { alert('Application failed to save.'); });
}
I'm using the example on the JQuery documentation as a base with some advice from here, here, and here. I've tried it with and without processData: false and it makes no difference.
When the call comes in to the Controller method the payload is null. If I post a simple string using some very similar code everything works fine. What precisely needs to be done in order to post XML to a Controller via $.ajax? Is it at the JavaScript or Controller end that the problem lies?
I eventually managed to find some hints on this and ended up with the following code:
$.ajax({
url: "/Data/SaveXML/",
type: "POST",
processData: false,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ payload: payload })
})
.done(function () { alert('Application saved.'); })
.fail(function () { alert('Application failed to save.'); });
The crucial differences are that the contentType is set to application/json, the data is turned into an object which is then run through the JSON.stringify method to make sure that the various characters that are unsuitable for a querystring can be sent without failing.
The default model binding doesn't work with processData set to false. If ServerXml is a string of XML, removing this should make it work:
function SendXmlToServer(ServerXml) {
$.ajax({ url: "/Home/XmlData",
type: "POST",
data: { ResXml: ServerXml }, dataType: "xml",
success: function () {
alert("Successful");
return false;
}
});
}
You'll also have to add the ValidateInput attribute to your action method, because normally "HTML markup" isn't allowed:
[HttpPost]
[ValidateInput(false)]
public ActionResult XmlData(string ResXml)
{
return null;
}
Alternatively, you could use custom model binding to seamlessly deserialize the XML, as explained in this blog post url https://lostechies.com/jimmybogard/2011/06/24/model-binding-xml-in-asp-net-mvc-3/.
I believe you may need to name the parameter you are passing to the controller.
So, something like...
var data = '<?xml version="1.0" encoding="utf-8"?><data>XML_GOES_HERE</data>';
$.ajax({
url: "/Data/SaveXML/",
type: "POST",
processData: false,
contentType: "text/xml",
data: { payload: data }
})

Categories

Resources