on the client side, I do
$.ajax({
url: '/emplacements/keyexist',
type: "POST",
data: JSON.stringify(postData),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
However the values in the action method are always 'null'
[AcceptVerbs("GET", "POST")]
public IActionResult KeyExist(
string nom, //[Bind(Prefix = nameof(EmplacementDTO.Nom))],
int id //[Bind(Prefix = nameof(EmplacementDTO.Id))]
)
{
// nom == null
// id == 0
how to fix it?
first make a model for your payload like below.
public class MyPayload
{
public string Nom{ get; set; }
public int Id { get; set; }
}
and inside your controller Action method
public IActionResult KeyExist([FromBody] MyPayload payload)
[FromBody] will automatically map the request body if property names are matched.
and your ajax call has another issue that you sending the Id as string but the Controller expect an int
Related
I am trying to send JSON to a class and it seems straightforward but for some reason it always shows up as null? Here's the situation:
AjaxCall is triggered by a change event. The url is correct, type is set to POST, and data is already converted with JSON.stringify() and logs as {"country":"Canada"}
function AjaxCall(u, d, t){
console.log(d);
return $.ajax({
url: u,
type: t ? t : 'GET',
data: d,
dataType: 'json',
contentType: 'application/json'
});
}
The class is triggered, but the country string is always null.
[HttpPost]
public JsonResult GetProv(string country)
{
//do whatever
}
What am I missing?!
Edit:
My Model:
public class country
{
public int Id { get; set; }
public string Name { get; set; }
}
I have created a JSON in jQuery which looks like this:
{
"objects":[
{
"ObjectId":1,
"Line1":"Software",
"Line2":"Microsoft",
"Line3":"Web",
"Line4":"Asp.Net",
"Line5":"jQuery"
},
{
"ObjectId":2,
"Line1":"Hardware",
"Line2":"Microsoft",
"Line3":"Computer",
"Line4":"Surface",
"Line5":"Pro"
}
]
}
Now I use AJAX to send it via jQuery to my controller:
var postData = { objects: objectArray };
// Fire off the request to controller
$.ajax({
cache: false,
url: '/Controller/myAction',
type: "POST",
dataType: 'html',
data: postData,
success: function (result) {
// success handler
}
})
public ActionResult myAction(???)
{
return view();
}
What I am not sure about is how I receive the object in my controller. Can someone help me with this please.
Thanks in advance!
Just a little lifehack for future: if you have to add new class based on existing JSON or XML model, there are awesome built-in tool in Visual Studio:
Class generating from JSON/XML models
This should work, start by creating a model object to represent the data on the server side
public class ObjectModel
{
public string ObjectId { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
public string Line4 { get; set; }
public string Line5 { get; set; }
}
Then define your mvc actions parameter like this
[HttpPost]
public ActionResult myAction(List<ObjectModel> objects)
{
return view();
}
then simply pass the object array as json
// Fire off the request to controller
$.ajax({
cache: false,
url: '/Controller/myAction',
type: "POST",
contentType: "application/json",
dataType: 'json',
data: JSON.stringify(objectArray),
success: function (result) {
// success handler
}
})
This is my class ARecipe :
public class ARecipe
{
public string picture { get; set; }
public string title { get; set; }
public int cookingTime { get; set; }
public int preparationTime { get; set; }
public string IngredientList { get; set; }
public string ingredientsDescription { get; set; }
public int nbPersons { get; set; }
public string Category { get; set; }
public string difficulty { get; set; }
public double nbStars { get; set; }
}
My Ajax call :
var dico = {
picture: $("#fakeInput").val(),
title : $("#title").val(),
cookingTime : $("#cookingTime").val(),
preparationTime : $("#preparationTime").val(),
IngredientList : $("#ingredientListArea").val(),
ingredientsDescription : $("#preparationArea").val(),
nbPersons : parseInt($("#select-nb-Persons").val()),
Category : $("#select-category").val(),
difficulty: $("#select-difficulty").val(),
nbStars : 4
};
$.ajax({
url: "/AddRecipe/TempData",
type: 'POST',
success: function (e) {
//success event
},
///Form data
data: JSON.stringify(dico),
///Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false,
processData: false
});
And the method receiving the datas :
[HttpPost]
public ActionResult TempData(ARecipe recipe) {
return Json("");
}
My Ajax call well go to the TempData method but when I analyse the parameter 'recipe' with the debugger, I notice that all the fields are 'null'.
Why ?
Do you have a solution ?
Thank you
You are sending the data as JSON, but the server expects is as regular POST data. Just let the ajax method turn it into a regular POST request instead of forcing it into JSON:
///Form data
data: dico,
Just Correct these issues :
$.ajax({
url: "/AddRecipe/TempData",
type: 'POST',
dataType: 'json',
contentType: 'application/json',
success: function (e) {
//success event
},
///Form data
data: JSON.stringify(dico),
///Options to tell JQuery not to process data or worry about content-type
cache: false,
});
[HttpPost]
public JsonResult TempData(ARecipe recipe) {
return Json("");
}
Our very simple models:
public class OrderSubmissionProductViewModel
{
public int Id { get; set; }
public decimal Price { get; set; }
public int Qty { get; set; }
}
public class OrderSubmissionViewModel
{
public int CustomerId { get; set; }
public int AccountId { get; set; }
public OrderSubmissionProductViewModel[] Products { get; set; }
}
The AJAX:
$.ajax({
url: self.urlSubmitOrder,
data: JSON.stringify({ submission: submission }),
type: 'POST',
success: function () { alert("Submitted"); },
fail: function () { alert("Failed"); }
});
The MVC controller has this method signature:
public ActionResult SubmitAdminOrder(OrderSubmissionViewModel submission)
{ ... }
This is what the POST looks like:
{"submission":{"CustomerId":43,"AccountId":"20000","Products":[{"Id":4,"Price":100,"Qty":1},{"Id":6,"Price":14,"Qty":1}]}}
I can hit a breakpoint in the controller method, and the model is not null, but all of its properties are default values. It's not getting bound correctly. What am I doing wrong?
We're using ASP.Net MVC 4.
Make sure the submission object isn't empty and can you try adding a contentType to the ajax options?
$.ajax({
url: self.urlSubmitOrder,
data: JSON.stringify({ submission: submission }),
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function () { alert("Submitted"); },
fail: function () { alert("Failed"); }
});
Or take a look at this post Pass viewmodel with two objects to controller using Json
I'm trying to invoke a WCF service method using POST and sending data encoded as json but no matter what I keep getting a bad request error.
This is my method signature:
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest)]
public int Publish(List<MeasurementData> data)
This is my MeasurementData model definition:
[DataContract]
public class MeasurementData
{
[DataMember]
public string ReadingDate;
[DataMember]
public int Unit { get; set; }
[DataMember]
public string ParameterAbbreviation { get; set; }
[DataMember]
public decimal Measurement { get; set; }
}
And this is how I'm calling it from the client:
var data = '[{"Measurement": 12678967.543233, "ParameterAbbreviation": "String content", "ReadingDate": "String content","Unit": 2147483647}]';
$.ajax({
type: "POST",
url: "/SiennaAddMeasurement/Publish",
data: "{ 'data' : '" + data + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
}
});
Is there something I'm missing?
you can check this below post.
400 Bad Request HTTP Response using a WCF POST via JQuery
some one has already faced such an error it turned to be an error related to the parameters pass.
hope it can help