unable to Deserializ the form data Error !! Invalid JSON Primitive - json

I am unable to Deserialized my JASON Serialized FormData
Please review my code
///here its my JSON
$("#btn_pro_spc").click(function () {
var formdata = $("#Product_spec_from").serialize();
$.ajax({
url: '#Url.Action("UpdateProductSpecification", "LC_LabChecking")',
type: 'POST',
data: { formdata : formdata },
datatype:'json',
success: function (data) {
}
});
});
///here it controller
public JsonResult UpdateProductSpecification(string formdata)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
LabCheckingModel LCModel = jss.Deserialize<LabCheckingModel>(formdata);
return Json(jss);
}
I Am getting serialized data perfectly but unable to Deserialized :(
Invalid JSON Primitive

It is not necessary to use use JavaScriptSerializer to deserialize your model. The DefaultModelBinder will do all this for you. Change the script to
$("#btn_pro_spc").click(function () {
$.ajax({
url: '#Url.Action("UpdateProductSpecification", "LC_LabChecking")',
type: 'POST',
data: $("#Product_spec_from").serialize(), // change this
datatype:'json',
success: function (data) {
}
});
});
and change the controller method to
public JsonResult UpdateProductSpecification(LabCheckingModel model)
{
// the value of model will be correctly bound
return return Json(??);
}
Side note: not sure what you are trying to return (currently its an instance of JavaScriptSerializer which does not make sense)

Related

How to retrieve JSON data in controller in ASP.net Core?

i need to get data sent with JSON and save to model in asp.net controller
//JSON data
var dataType = 'application/json';
var data = {
ID: 'Zaki',
}
console.log('Submitting form...');
console.log(data);
$.ajax({
type: 'POST',
url: 'Save',
dataType: 'json',
contentType: dataType,
data: data,
success: function (result) {
console.log('Data received: ');
console.log(result);
}
});
Controller
[HttpPost]
public ActionResult Save([FromBody] string ID)
{
return Json (ID);
}
am getting null in console , it supposed to be zaki and from there i wanna write saving code...
Another way to do it is to simply use 'dynamic' type to handle json request data. Take a look:
[HttpPost]
public IActionResult YoutMethod([FromBody] dynamic requestData)
{
Log.Information(requestData.field1);
Log.Information(requestData.field2);
// ...
return Ok();
}
Modify this line in your code data: data, to
data:JSON.stringify(data)
When sending data to a web server, the data has to be a string and JSON.stringify method converts a JavaScript object into a string.
Another approach would be, instead of getting raw string value, wrap your parameter into a class object like this
public class ParamObj
{
public string ID{get;set;}
}
and in your controller get a parameter of this object type like this..
public ActionResult Save([FromBody] ParamObj data)
Thanx
I know that is already marked as answered, but here is another way to do it:
I am not using the binding FromBody attribute.
Controller
public class JsonRequest
{
public string Id { get; set; }
}
[HttpPost]
public ActionResult Save(JsonRequest data)
{
return Json(data.Id);
}
Instead of using dataType I am using accept and you don't need to convert your json into a string.
To avoid problems with relative paths I am using: url: '#Url.Action("Save", "Home")' as well.
Javascript
function send()
{
//JSON data
var dataType = 'application/json';
var data = {
"id": "Zaki"
}
console.log('Submitting form...');
console.log(data);
$.ajax({
type: 'POST',
url: '#Url.Action("Save", "Home")',
accept: dataType,
data: data,
success: function (result) {
console.log('Data received: ');
console.log(result);
}
});
}
Good luck with your project.

Return json array from client to spring controller

I need to send data from the client html back to the spring controller.
I have a controller which generates a Json array whichh I sent via ajax to the html side when requested.
That functions well.
The Problem is I need to send the Json array back to another controller for evaluation and changes.
If I post the data and assign an class object of the original class I get the error " Bad request" and it didn't work.
If I assign an object in the controller which consumes the post. That works
but I get an hashmap for which I dont know how to access.
I cant cast it to another class nor access it to work with it.
Since I am new to this can someone give me an advice how to consume the post
on the receiving controller side.
Thanks
Khelvan.
Controller code ist stated below
controller 1 for Get
#RequestMapping("/Person")
#ResponseBody
public ArrayList<Person> ajax_Person_array()
{
ArrayList<Person> Dummy = new ArrayList<Person>();
for ( x=0; x < 5; x++ ){
Dummy.setName("Alfon");
Dummy.setID("5");
Dummy.setStree("Delta");
Dummy.setName("Neutral");
Person.add(Dummy);
}
return Dummy;
}
Controller 2 for post
#RequestMapping(value="/ajax", method=RequestMethod.POST, consumes = "application/json")
//public #ResponseBody String post( #RequestBody Object ajax_Person_array()) {
public #ResponseBody String post( #RequestBody ArrayList<Person> ajax_Person_array()) {
System.out.println("First TEST");
String Success = "OK";
return Success;
}
Html : get ajax
var ajax_data;
$.ajax({
url: "http://localhost:8080/Person",
async: false,
dataType:'json',
cache: false,
success: function (data) {
ajax_data = data;
alert("success ");
},
error:function(){alert("something went wrong ");}
});
}
Html post ajax
$.ajax({
url: "http://localhost:8080/ajax",
type: 'POST',
dataType: 'text',
data: ajax_data,
// data: JSON.stringify(ajax_data),
contentType: 'application/json',
success: function(data) {
alert(data);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
document.write(data);
}
});
#RequestMapping (value="/ajax", method=RequestMethod.POST, consumes = "application/json")
public #ResponseBody JSONObject post( #RequestBody JSONObject person) {
//Pass data to a service to process the JSON
}
For your ajax request, do not set dataType to 'Text'. Set it to JSON
$.ajax({ url: "http://localhost:8080/ajax",
type: 'POST',
dataType: 'json',
data: JSON.stringify(ajax_data),
contentType: 'application/json',
success: function(data) {
alert(data);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
document.write(data);
}
});

Json Data Not mapped in the backend service

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');
}
});

How to pass a JSON object to an action

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;
}

Send generic JSON data to MVC2 Controller

I have a javascript client that is going to send json-formatted data to a set of MVC2 controllers. The client will format the json, and the controller will have no prior knowledge of how to interpret the json into any model. So, I can't cast the Controller method parameter into a known model type, I just want to grab the generic json and pass it to a factory of some sort.
My ajax call:
function SendObjectAsJSONToServer(object,url,idForResponseHTML) {
// Make a call to the server to process the object
var jsonifiedObject = JSON.stringify(object);
$.ajax({
url: url // set by caller
, dataType: 'json'
, data: jsonifiedObject
, type: 'GET'
, error: function(data) { alert('error in sendObjectAsJSONToServer:' + data); }
, success: function(data) {
alert(data.message); // Note that data is already parsed into an object
}
});
}
My MVC Controller:
public ActionResult SaveForm(string obj)
{
// Ok, try saving the object
string rc = PassJSONToSomething(obj.ToString());
string message = "{\"message\":\""+rc+"\",\"foo\":\"bar\"}";
return new ContentResult { Content = message, ContentType = "application/json" };
}
The problem is that obj is always null. Can anyone tell me how I should structure the ajax call and the controller parameter so that I get my json to the server? I'm using MVC2. This may appear to be a duplicate of some SO questions, but in my case I do not know the Model that the json maps to, so I can't use a specific model type in the controller parameter type.
Thanks very much.
Have you tried something like that?
$.ajax({
url: url // set by caller
, dataType: 'json'
, data: {obj :jsonifiedObject}
, contentType: 'application/json; charset=utf-8'
, type: 'GET'
, error: function(data) { alert('error in sendObjectAsJSONToServer:' + data); }
, success: function(data) {
alert(data.message); // Note that data is already parsed into an object
}
});