I'm trying to send a json object (extjs client ) to asp.net server side application:
This is the request (with sample data but same logic):
var datiOrdine = [];
for (i = 0; i < elencoChk.length; i++)
{
datiOrdine.push
({
x: arr[i].value1, // string
y: arr[i].value2, // string
z: arr[i].value3, // string
k: arr[i].value4, // string (dd/MM/yyyy)
l: arr[i].value5, // double
});
}
Ext.Ajax.request({
url: '/RAMMVC/RDA/UpdateRDA',
params: { array: Ext.JSON.encode(datiOrdine) },
headers: { 'Content-Type': 'application/json; charset=utf-8' },
method: "POST",
success: function (response) {},
failure: function (response) {}
});
The json object:
[
{
"x":"GRT02",
"y":"0215000050",
"z":"0001",
"k":"30/01/2015",
"l":1413.5
}
]
And this is the method I declare on server side web application:
public ActionResult UpdateRDA(?)
{
}
How can I declare the param(?) on UpdateRDA method to receive correctly the json object? Missing any annotations?
If I declare
public ActionResult UpdateRDA(string array)
{
}
I get Invalid Json Primitives exception.
Programming languages:
client UI: extjs 4.1
server: asp.net MVC 3, net framework 4.0
I was able to get your example working with a few small changes on similar setup (MVC3, ExtJS 4.2).
For your Ajax request you don't need 'method' as 'post' will be the default when parameters are present. Also, I am not familiar with the 'headers' property, I only know of 'defaultHeaders'. In any case you should not have the headers property set.
Here's what I used as a test case:
var datiOrdine = [];
for (i = 0; i < 10; i++) {
datiOrdine.push({
x: "GRT02", // string
y: "0215000050", // string
z: "0001", // string
k: "30/01/2015", // string (dd/MM/yyyy)
l: 1413.5, // double
});
}
Ext.Ajax.request({
url: '/myserver/Controller/Method',
params: {
array: Ext.JSON.encode(datiOrdine)
},
success: function (response) {
alert('yes');
},
failure: function (response) { }
});
The server side method:
public ActionResult Test(string array)
{
var test = array;
return Content("");
}
public ActionResult UpdateRDA(FormCollection collection)`
{
// TODO
}
Related
I have a razor view which calls a method on an MVC controller via Ajax. All is working except I am not receiving anything back even though I am returning a JSON result. The "data" element in the success portion is undefined.
Here is the Ajax call:
callback: function(result) {
if (result === true) {
$.ajax(
{
type: "POST", //HTTP POST Method
url: "AddEmployee", // Controller/View
data: { //Passing data
Name: $("#txtName").val(), //Reading text box values using Jquery
City: $("#txtAddress").val(),
Address: $("#txtcity").val(),
Phone: $("#txtPhone").val(),
SSN: $("#txtSsn").val(),
success: function (data) {
alert(data.ResponseMessage);
//$('<div>' + data + '</div>').appendTo('#divConfirm');
}
}
});
Here is my controller:
[HttpPost]
public JsonResult AddEmployee(EmpModel obj)
{
bool isSaved = AddDetails(obj);
Response response = new Response {ResponseMessage = "Success!"};
return Json(response);
}
You put wrong } in data, my friend:
Name: $("#txtName").val(), //Reading text box values using Jquery
City: $("#txtAddress").val(),
Address: $("#txtcity").val(),
Phone: $("#txtPhone").val(),
SSN: $("#txtSsn").val() },
success: function (data) {
alert(data.ResponseMessage);
//$('<div>' + data + '</div>').appendTo('#divConfirm');
}
I am trying to pass a JSON array into spring MVC Controller like such:
var myList = new Array();
data._children.forEach( function (d) {
myList.push( {NAME: d.name, TYPE: d.TYPE, FDATE: d.FDATE } );
});
$.post("/ListRequest", {myList: myList});
The controller looks as such:
#RequestMapping(value="/ListRequest", method = RequestMethod.POST)
public void ListRequest(#RequestParam("myList") myList tempmyList )
{
System.out.println(tempmyList);
}
The class myList defined as such:
public class MyList {
private List<ListT> ListT;
public List<ListT> getListT() {
return ListT;
}
public void setListT(List<ListT> listT) {
ListT = listT;
}
}
ListT class:
public class ListT {
private String NAME;
private String TYPE;
private Long FDATE; ...
I keep getting this error:
HTTP Status 400 - Required myList parameter 'myList' is not present
Also tried this request:
$.ajax({
type: "post",
url: "ListRequest", //your valid url
contentType: "application/json", //this is required for spring 3 - ajax to work (at least for me)
data: JSON.stringify(myList), //json object or array of json objects
success: function(result) {
//do nothing
},
error: function(e){
alert('failure');
}
but get this error: JBWEB000120: The request sent by the client was syntactically incorrect.
try to add this to you ajax call it should fix the unsupported response :
headers : {
'Accept' : 'application/json',
'Content-Type' : 'application/json'
},
this is a full example of ajax call that is working for me :
$.ajax({
dataType : "json",
url : this.baseurl + "/dataList",
headers : {
'Accept' : 'application/json',
'Content-Type' : 'application/json'
},
data : JSON.stringify(params),
type : 'POST',
success : function(data) {
self.displayResults(data);
},
error : function(jqXHR,textStatus,errorThrown ){
showPopupError('Error','error : ' + textStatus, 'ok');
}
});
Even I was facing same problem.
My client request was right and generated proper json file.
but still i was getting same error.
I solved this error using #JsonIgnoreProperties(ignoreUnknown = true) in pojo class.
refer this link.
Spring MVC : The request sent by the client was syntactically incorrect
You can try
#RequestParam("myList") myList tempmyList
#Param myList tempmyList
in addition, class names must begin with a capital letter.
I have a Spring MVC web application and I have the following web service.
#RequestMapping(value = "/newBill", method = RequestMethod.POST)
public #ResponseBody ModelMap acceptNewBill(#ModelAttribute ("Bill") Bill newBill ){
Bill bill = new Bill();
bill.setTableName(newBill.getTableName());
bill.setRoom(newBill.getRoom());
bill.setCovers(newBill.getCovers());
ModelMap model = new ModelMap();
model.put("status", true);
return model;
}
The following Script performs the front end functions.
$('.done').click(function(){
var jsonObject = createJSON(".newBill");
jQuery.ajax({
url: "/newBill",
type: "POST",
data: {bill: JSON.stringify(jsonObject) },
dataType: "json",
beforeSend: function(x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success: function(result) {
alert('sadgsd');
}
});
});
function createJSON(elementToConvert) {
jsonObj = [];
$( elementToConvert + " input").each(function() {
var id = $(this).attr("class");
var email = $(this).val();
item = {}
item [id] = email;
jsonObj.push(item);
});
return jsonObj;
}
The above createJSON function go through a provided html element and puts the values into an object! The click function performs the POST and the Post contains the following data.
bill [{"tableName":"326432"},{"room":"3462346"},{"covers":"3426234"}]
Now when I debug and check the service, the data which goes from the front end doesn't get mapped in the parameter. I checked whether the variable names are the same as the POST. They are the same! but the values doesn't get mapped! Can any one please help me with this issue.
Update :
I changed the service method to GET and passed a value as a URL variable. Then it got mapped in the service param. The problem is in the POST.
Instead of using #ModelAttribute in your controller use #RequestBody:
public #ResponseBody ModelMap acceptNewBill(#RequestBody Bill newBill) {
On the ajax call, set the content type to application/json and stringify the whole object instead of just the array:
jQuery.ajax({
url: "/newBill",
type: "POST",
data: JSON.stringify({bill: jsonObject}),
dataType: "application/json",
beforeSend: function(x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success: function(result) {
alert('sadgsd');
}
});
I'm using MVC web Api for RESTful purpose. My controller methods return serialized Json object in string format. I've got some simple method like this:
public string Put(Folder folder)
{
var folder1 = new Folder{Id="1", IsShared=true,Name= folder.Name};
var jsSerializer = new JavaScriptSerializer();
return jsSerializer.Serialize(folder1);
}
I call Get, Put, Delete and Post methods in QUnit test like this and it works fine:
ajax: {
getData: function (url, data) {
return processRequest(url, data, "GET");
},
postData: function (url, data) {
return processRequest(url, JSON.stringify(data),"POST");
},
updateData: function (url, data) {
return processRequest(url, JSON.stringify(data),"UPDATE");
},
deleteData: function (url, data) {
return processRequest(url, JSON.stringify(data),"DELETE");
},
processRequest: function (url, data, type) {
return $.ajax({
type: type,
dataType: "json",
contentType: "application/json;charset=utf-8",
url: url,
data: data,
processData: true
});
}
},
I need to change return value from string to actual Json object because my client doesn't want serialized Json anymore. They need actual Json object. So I changed the method return type to JsonValue and parse the serialized Json object using JsonValue.Parse() method. When I trace my codes in server side, JsonValue object has proper values in its properties and looks fine but the returned JsonValue in client side has empty properties. here is changed method:
public JsonValue Put(Folder folder)
{
var folder1 = new Folder{Id="1", IsShared=true,Name= folder.Name};
var jsSerializer = new JavaScriptSerializer();
return JsonValue.Parse(jsSerializer.Serialize(folder1));
}
here is test result:
Expected:
{
"Id": "1",
"IsShared": true,
"Name": "abc"
}
Actual:
{
"Id": [],
"IsShared": [],
"Name": []
}
I appreciate any idea.
What I did to fix is adding Newtonsoft.Json.dll to my project and using Newtonsoft.Json.Linq.JToken instead of using System.Json.JsonValue. here is my method implementation:
public Newtonsoft.Json.Linq.JToken Put(Folder folder)
{
var folder1 = new Folder{Id="1", IsShared=true,Name = folder.Name};
var jsSerializer = new JavaScriptSerializer();
return Newtonsoft.Json.Linq.JObject.Parse(jsSerializer.Serialize(folder1));
}
and if you have an array of JSON, you need to parse like this:
public Newtonsoft.Json.Linq.JToken Put(IList<Folder> folders)
{
var folder1 = new Folder{Id="1", IsShared=true,Name = folder.Name};
var jsSerializer = new JavaScriptSerializer();
return Newtonsoft.Json.Linq.JArray.Parse(jsSerializer.Serialize(folders));
}
I have the following jQuery code in a View in MVC3. I want to load a partial view (named OffshoreECore) in a div (#Form) depending on the JSON object passed in the success function. Here's the code:
var inputParamtrs = { 'HeadId': $('#ExpenseId').val(), MProjid': $('#MProjid').val() };
$.ajax({
type: "POST",
url: "/Expenses/Edit",
data: inputParamtrs,
success: function (json) {
('#Form').load('#Url.Action("OffShoreECore", *What comes here ?!?*)');
}
Thanks.
The second parameter of load() is the data which should be sent to the specified URL along with the request. To send your JSON string, try this:
success: function (json) {
$('#Form').load('#Url.Action("OffShoreECore")', json);
}
You example code is also missing a ' delimiter from the second key in inputParamtrs and the $ from the selector in success, but I guess they're just typos.
$.getJSON("/Expenses/Edit",
{
HeadId: $('#ExpenseId').val(),
MProjid: $('#MProjid').val()
},
function (data) {
elementForResult.innerHTML = data;
});
In Controller:
public JsonResult Edit(int HeadId, int MProjid)
{
...
var result = SerializeControl("~/Views/Expenses/Edit.cshtml", null);
return Json(result, JsonRequestBehavior.AllowGet);
}
private string SerializeControl(string controlPath, object model)
{
var control = new RazorView(ControllerContext, controlPath, null, false, null);
ViewData.Model = model;
var writer = new HtmlTextWriter(new StringWriter());
control.Render(new ViewContext(ControllerContext, control, ViewData, TempData, writer), writer);
string value = writer.InnerWriter.ToString();
return value;
}