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.
Related
I'm trying to pass the model from the view to controller using AJAX, the AJAX call works with a hard-coded JSON string but fails with the actual JSON and I don't know why, any help is very appreciated. Step by step this is what I did:
In the view I have
<script>
var FeedData = #Html.Raw(Json.Serialize(Model));
</script>
In My JavaScript file
var index= $(this).val();
var test = window.FeedData[index];
var json = {
prop1: 'test',
prop2: 'test2',
};
var data = {
json: JSON.stringify(json)
};
var data2 = {
json: JSON.stringify(test)
};
$.ajax({
type: 'GET',
dataType: 'json',
url: "/Feed/GetFeedDetails",
data: data,
success: function (json) {
if (json) {
alert('ok');
} else {
alert('failed');
}
},
});
Ok, Both data and data2 variables are JSON stringified..
data: data, // Works
data: data2,//this does not work
My Controller
public async Task<PartialViewResult> GetFeedDetails(string json)
{
Feed feedData = JsonConvert.DeserializeObject<Feed>(json);
return PartialView("FeedDetailsModal", feedData );
}
Any help is much appreciated.
the AJAX call works with a hard-coded JSON string but fails with the actual JSON and I don't know why
In your code, we can find that you set Ajax request method to 'GET', so the data would be passed through query string, if you can not get expected data in action method, please use browser developer tools Network tool to capture request and check if well-formatted data is passed.
Besides, your action method accepts string-type parameter and manually convert to a Feed object, to achieve same, you can try to make action method accept Feed type parameter and make it automatically bind value to properties of model class via model binding feature.
public IActionResult GetFeedDetails([FromBody]Feed feed)
{
//...
Pass complex data through request body instead of in query string, like below.
var data2 = window.FeedData[index];
$.ajax({
type: 'Post',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: "/Feed/GetFeedDetails",
data: JSON.stringify(data2),
success: function (json) {
if (json) {
alert('ok');
} else {
alert('failed');
}
},
});
Test Result
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',
...
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
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
}
}
I am trying to sent a byte[] in a postback action, but failed to get it.
Code snippets:
$.ajax({
url: proxy.Model.RequestParamUrl,
type: "Post",
async: false,
data: proxy.requestArgs,
dataType: 'json',
success: function (Jsondata) {
proxy.allowPost = false;
proxy.postSucceed = true;
//hidden code
return true;
}
});
While debugging, I can see byte[] in proxy.requestArgs.
But in the controller, I get null in this action result.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(byte[] param)
{
//I get null in this param.
}
Anything I am missing out?
Any Solution
You're passing data to the controller action and that action is expecting a post item named param. So in your JS, make your ajax call look like this (note the change to data):
$.ajax({
url: proxy.Model.RequestParamUrl,
type: "Post",
async: false,
data: { param: proxy.requestArgs },
dataType: 'json',
success: function (Jsondata) {
proxy.allowPost = false;
proxy.postSucceed = true;
//hidden code
return true;
}
});
Have you tried this?
Basically, accept the data as string in you action and inside it convert it into byte[]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(string param)
{
var bytes = System.Text.Encoding.UTF8.GetBytes(param);
}