AJAX call with parameters not working - javascript

I've got troubles making an ajax post with parameters to my controller. While this works:
$.post("../api/vorgang/blubb");
[HttpPost]
[Route(#"blubb")]
public void blubb()
{
// do amazing things here
}
The method is not being hit when I extend it for parameters:
$.post("../api/vorgang/blubb", { param1: "param1", param2: "param2"} );
[HttpPost]
[Route(#"blubb")]
public void blubb(string param1, string param2)
{
// method is not hit, why oh why
}
// the request text
param1=param1&param2=param2
I see that it results in
404: "no HTTP-Resource could be found that fits the URI http://localhost:49412/api/vorgang/blubb.
I have tried changing the ajax call to
$.post("../api/vorgang/blubb", JSON.stringify({
param1: "param1",
param2: "param2"
}));
this changes the request text to
{"param1":"param1","param2":"param2"}
but the controller still does not get hit.
I'd be thankful for a hint!

The way you are passing parameter's with HttpPost, I am not sure if it's gonna work. Was going thru FromBody approach mentioned here.
Alternatively, you could try creating a Model object and let the MVC do the heavy lifting.
public class TestController : ApiController
{
[HttpPost]
public void blubb(Parameters param1)
{
// method is not hit, why oh why
}
}
public class Parameters
{
public string param1 { get; set; }
public string param2 { get; set; }
}
Your AJAX call:
var _parameters = {
param1: "param1",
param2: "param2"
};
$.ajax({
type: "POST",
url: "/api/Test/blubb",
cache: false,
data: JSON.stringify(_parameters),
contentType: "application/json; charset=utf-8",
success: function (data) { console.log("Success"); }
});
Final Result :
Not sure, how much will it help!

Related

json string on POST to MVC action method using AJAX is null

I am getting a hard time to find out why the string sent via AJAX request is null. Console.WriteLine(data) shows empty. Status is 200 OK. If I add some code to parse the string received, I get an error stating that JObject.Parse cannot be null. I don't know what am I missing. The javascript code is ok. The action method also seems ok, but my knowledge on Asp.Net Core and MVC is very scarce, so I am not sure. Can someone please point out what am I missing?
The javascript code:
let obj = {email: email_address.value};
let objStringified = JSON.stringify(obj);
$.ajax({
type: 'POST',
contentType: 'application/json; charset=UTF-8',
data: objStringified,
url: '#Url.Action("ReturnCheckAccountDuplication")',
dataType: 'text',
success: function(data) {
console.log(data);
},
error: function(error) {
console.log("Keep trying", error);
}
});
C# code:
[HttpPost]
public ActionResult ReturnCheckAccountDuplication([FromBody] string data)
{
Console.WriteLine(data);
JObject jObject = JObject.Parse(data);
string email = (string)jObject["email"];
bool emailExists = CheckAccountDuplication.Get(email);
string returnResult = emailExists.ToString();
return Content(returnResult);
}
The solution on the controller side is
public class AccountCheckModel
{
public string Email { get; set; }
}
[HttpPost]
public ActionResult ReturnCheckAccountDuplication([FromBody] AccountCheckModel data)
{
string result = CheckAccountDuplication.Get(data.Email).ToString();
return Content(result);
}
Thanks to all the members who commented on my problem, especially John Glenn who provided a solution. I had been trying for several days but without success. My knowledge of Asp.Net Core is very poor indeed. Thank you very much.
The easiest solution is to create a model representing the JSON data that your controller will receive. For example, create a class like so:
public class AccountCheckModel
{
public string email { get; set }
}
Then, use it as the parameter for your controller method:
public ActionResult ReturnCheckAccountDuplication([FromBody] AccountCheckModel data)
This is the preferred way to access the request body. To get the request body as a string, you have to jump through some serious hoops.
An alternative way to send your data via AJAX to your Controller:
var json = {
email: email_address.value
};
$.ajax({
type: 'POST',
data: {'json': JSON.stringify(json)},
url: '#Url.Action("ReturnCheckAccountDuplication")',
dataType: 'json',
success: function(data) {
console.log(data);
},
error: function(error) {
console.log("Keep trying", error);
}
});
And your Controller:
[HttpPost]
public ActionResult ReturnCheckAccountDuplication(string json)
{
Console.WriteLine(json);
JObject jObject = JObject.Parse(json);
string email = (string)jObject["email"];
bool emailExists = CheckAccountDuplication.Get(email);
string returnResult = emailExists.ToString();
return Content(returnResult);
}

ASP.NET: Ajax doesn't send string

I have this method to send some data with ajax:
function SendData(foodID, basketID) {
var data = { FoodID: foodID, BasketID: basketID };
$.ajax({
url: '/Order/Post',
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json;utf-8',
datatype: 'json'
}).done(function (data) {
console.log(data);
}).fail(function (data) {
console.log("Error: " + data);
});
}
In C#, my Post Method in my Order controller gets triggered, but the string I want to hand over is null:
public bool Post(string s)
{
//When this gets executed, s is null
return true;
}
I tested this by executing SendData(1,1) directly on a button click. What is the mistake I'm doing and how can I get the string in my Post-Method?
you are post the object. not string.
you can try generate to object and load this object. or add new one parameter to action (foodId and basketId but you must post like that if you check this option data:{foodId,basketId})
//model
public class SomeObject{
public string FoodId {get;set;}
public string BasketId {get;set;}
}
//code
public bool Post(SomeObject data)
{
return true;
}
It seems for me your data structure to the Post action doesn't match action parameter names. Try this:
[HttpPost]
public bool Post(string foodID, string baskedID)
{
return true;
}
I believe you have to name your data that's being passed like so:
data: { 's': JSON.stringify(data) }

404 Not Found in AJAX post call

I'm using Spring MVC and when I do an ajax post call I get a 404. My controller looks like this:
#Controller
#RequestMapping("/mensaje")
public class MensajeController {
public MensajeController() {
super();
}
#ResponseBody
#RequestMapping(value = "/prueba", method = RequestMethod.POST)
public String prueba(#RequestParam("cuerpo") final String cuerpo) {
String b = null;
String a = null;
return b;
}
}
And the ajax call like this:
<script type='text/javascript'>
$(document).ready(function() {
$("#save").click(function(e) {
e.preventDefault();
var myEditor = document.querySelector('#editor');
var html = myEditor.children[0].innerHTML;
$.ajax({
type : "POST",
url : "/Gestion-Practicas/mensaje/prueba",
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: {'cuerpo': html},
async: false,
cache: false,
delay: 15,
success: function(data){
alert('success');
},
error: function (xhr) {
alert(xhr.responseText);
}
});
});
});
</script>
The url from where I do the ajax call is:
http://localhost:8080/Gestion-Practicas/mensaje/create.do
The url who appears in the Chrome's console after doing the ajax call is:
http://localhost:8080/Gestion-Practicas/mensaje/prueba
Summarizing, the ajax call never reaches the controller's method and I don't know why
Instead of #RequestParam use #RequestBody
#RequestParam - It's used for query parameters in request url.
#RequestBody - It's a post body payload.
Convert your String cuerpo to a class with property String cuerpo
public class PostBody{
private String cuerpo;
public String getCuerpo(){
return this.cuerpo;
}
public void setCuerpo(String cuerpo){
this.cuerpo = cuerpo;
}
}
Now your line public String prueba(#RequestParam("cuerpo") final String cuerpo)
Updated will look like public String prueba(#RequestBody final PostBody postBody).

getting null value in list when passing by ajax call to mvc controller

I am passing my list to an mvc controller but I am getting null value in the controller.But my list has values when show in alert on client side.
ajax call
$("#addTiles").click(function() {
userTiles = JSON.stringify({
'userTiles': userTiles
});
alert("Entered function.");
alert(userTiles[0].TileID);
var url = '#Url.Action("AddTiles")';
$.ajax({
type: "GET",
url: url,
data: userTiles,
success: function(d) {
if (d.indexOf('"IsSessionExpired":true') != -1) {
location.reload();
} else {
onAddTilesSuccessful(d);
}
},
error: function() {
errorInOperation();
},
contentType: "application/html; charset=utf-8",
dataType: 'html'
});
});
function onAddTilesSuccessful(e) {
$("#tilesSubmissionMsg").append(e);
}
function errorInOperation(d) {
$("#tilesSubmissionMsg").append("Something went wrong");
}
mvc controller
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
List Model
public class UserTilesVM
{
public int TileID { get; set; }
public int TopPosition { get; set; }
public int LeftPosition { get; set; }
}
List in javascript
"{"userTiles":[{"TileID":"3","TopPosition":0,"LeftPosition":0}]}"
I have also tried by sending my list with stringfy but that also doesn't work.
Use : [HttpGet] on the method AddTiles as you have used type: "GET" on the Ajax hit.
[HttpGet]
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
If Still doesn't works then try type: "POST" on Ajax hit and on method use [HttpPost]
[HttpPost]
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
You have contentType and dataType twice in your AJAX setup, with different values, which will break the AJAX call.
Keep in mind contentType is to tell the server what type of data to expect and dataType is to determine what type of data is returned, from the documentation.
Edit: I see you have edited your code!
In this case, since you are using JSON.Stringify to modify the data you are sending, you would use contentType: "application/json; charset=utf-8", as your contentType, since you are sending JSON data to the backend.
when we are trying to pass object data using ajax, we have to store data in variable and pass data directly using "data :'variable'" in AJAX to Controller Method
$("#addTiles").click(function() {
var userTiles = ({
'userTiles': userTiles
});
alert("Entered function.");
alert(userTiles[0].TileID);
var url = '#Url.Action("AddTiles")';
$.ajax({
type: "POST",
url: url,
data: userTiles,
success: function(d) {
if (d.indexOf('"IsSessionExpired":true') != -1) {
location.reload();
} else {
onAddTilesSuccessful(d);
}
},
error: function() {
errorInOperation();
},
contentType: "application/html; charset=utf-8",
dataType: 'html'
});
});
function onAddTilesSuccessful(e) {
$("#tilesSubmissionMsg").append(e);
}
function errorInOperation(d) {
$("#tilesSubmissionMsg").append("Something went wrong");
}
//Use [HttpPost] keyword for getting value which was passed by AJAX.
[HttpPost]
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
I think your list definition is not ok:
"{"userTiles":[{"TileID":"3","TopPosition":0,"LeftPosition":0}]}"
should be:
"{"userTiles":[{"TileID":"3","TopPosition":"0","LeftPosition":"0"}]}"
i have using this sequence that work fine
you have check the
contentType: "application/json",
dataType: "json",
sequence in ajax method

How to pass a javascript object to a C# MVC 4 controller

In MVC4, how do you pass a javascript object to a C# controller in AJAX?
Finally I tried this but it did not work.
Javascript Client side:
var myData = {Propr1: '', Propr2: ''};
$.ajax({
type: 'POST',
data: JSON.stringify(myData),
url: '/Home/SubmitMyData',
contentType: 'application/json',
dataType: 'json',
success: alert('Youhou'),
error: alert('not good')
});
C# Server side method:
public ActionResult SubmitMyData(MyParamModel myParam)
{
// Do my stuff here with my parameter
return View();
}
public class MyParamModel
{
string Prop1 { get; set; }
string Prop2 { get; set; }
}
My parameter is always null. I tried to change the contentType but it still not work.
Where are my mistakes? I found some posts but I did not find what I did wrong.
Thanks a lot.
Make sure the property names match between the javascript and the C# model. In your question you had Propr1 and Propr2 for the javascript object, but in the C# model you had Prop1 and Prop2 (missing the "r").
Do not stringify the data before sending it, and do not set dataType to json. MVC can parse just fine with a collection of post parameters without the json serialization in your code.
Omit the contentType, it is not necessary. WebAPI should autodetect this. You can leave it, but it's extraneous.
Make sure the model properties are public.
Javascript Client side:
var myData = {Prop1: '', Prop2: ''}; // #1
$.ajax({
type: 'POST',
data: myData, // #2
url: '/Home/SubmitMyData',
//contentType: 'application/json', #3
//dataType: 'json', #2
success: alert('Youhou'),
error: alert('not good')
});
C# Server side method:
public ActionResult SubmitMyData(MyParamModel myParam)
{
// Do my stuff here with my parameter
return View();
}
public class MyParamModel // #4
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
The value you pass for the data property should be an object, not a string:
data: myData,
the property names need to match:
var myData = { Prop1: '', Prop2: ''};
you need to use the [FromBody] attribute on your parameter value:
public ActionResult SubmitMyData([FromBody] MyParamModel myParam)
and the properties on your model type need to be public:
public class MyParamModel
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}

Categories

Resources