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
Related
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!
I want to call a controller method with an Ajax call. If this is called, another view should be returned.
When I debug the code, I also reach my controller method. However, the new view is not displayed.
What am I doing wrong?
Controller:
public ActionResult RequestDetails(string requestId, string requestState)
{
// ToDo handle parameter
return View();
}
JS:
ShowDetails = function (e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
$.ajax({
type: 'GET',
data: {
'requestId': dataItem.RequestId,
'requestState': dataItem.RequestState
},
url: "/Controller/RequestDetails",
contentType: 'application/json; charset=utf-8'
});
}
What I am doing wrong?
best regards
It wouldn't show unless you direct it about what to do with the result that is returned from the ajax call.
You would need to create a container html element on the main View which is currently being displayed on the page firstly:
<div id="RequestDetailsContainer">
</div>
and then in the success callback you will need to put the html returned by controller action to be displayed in that div :
$.ajax({
type: 'GET',
data: {
'requestId': dataItem.RequestId,
'requestState': dataItem.RequestState
},
url: "/Controller/RequestDetails",
contentType: 'application/json; charset=utf-8',
success: function(response) { // note this function
$("#RequestDetailsContainer").html(response);
}
});
A side note about the url property that, you should be using Url.Action for generating the urls instead of using string literals like:
url: "#Url.Action("RequestDetails","Controller")"
Hope it helps.
I'm new in asp.net core, c# and MVC 6. I'm trying to send data over ajax to my controller.
function ajaxMethodData() {
$.ajax({
url: "AjaxWithData", // hard coded for testing
type: "POST",
data: JSON.stringify({ username: "NeXT405" }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
},
error: function () {
alert('error');
}
});
}
The method in the controller looks like this. The method gets invoked by the ajax request.
[HttpPost]
public IActionResult AjaxWithData([FromBody] string username )
{
Debug.WriteLine(username);
return Json(new { success = true } );
}
It looks like the data has been sent right.
If I have understood it correctly the string should now have the value from the passed data. But it is still null.
I have also tried it with void as return value (and no dataType).
<input type="button" value="Fatty2" onclick="ajaxMethodData()" />
What I'm doing wrong?
Just change
data: JSON.stringify({ username: "NeXT405" }),
To
data: JSON.stringify("NeXT405"),
WebApi only allow to get 1 parameter from body, so the variable name is not needed for basic types.
Just check: https://www.asp.net/web-api/overview/advanced/sending-html-form-data-part-1
The last example is exactly your case
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 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 }
})