Unable to convert Javascript object to Java Model - javascript

My Spring controller and client side Javascript code are as follows and for some reason the Javascript object is unable to reach the Spring controller in the Object form. My Controller code is as follows:
#RequestMapping(value = "/addRating", method = RequestMethod.POST, headers = "Accept=application/json")
public EmployeeRating addRating(#ModelAttribute("employeeRating") EmployeeRating employeeRating) {
if(employeeRating.getId()==0)
{
employeeRatingService.addRating(employeeRating);
}
else
{
employeeRatingService.updateRating(employeeRating);
}
return employeeRating;
}
My Javascript code below:
$.ajax({
url: 'https://myrestURL/addRating',
type: 'POST',
dataType: 'json',
data: {
'id':5,
'name': 'Name',
'rating': '1'
},
contentType: 'application/json; charset=utf-8',
success: function (result) {
// CallBack(result);
window.alert("Result: " + result);
},
error: function (error) {
window.alert("Error: " + error);
}
});
The EmployeeRating object in Java has id, name and rating fields so there's no mismatch.
Updating the model class
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/*
* This is our model class and it corresponds to Country table in database
*/
#Entity
#Table(name="EMPLOYEERATING")
public class EmployeeRating {
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
int id;
#Column(name="name")
String name;
#Column(name="rating")
long rating;
public EmployeeRating() {
super();
}
public EmployeeRating(int i, String name,long rating) {
super();
this.id = i;
this.name = name;
this.rating=rating;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getRating() {
return rating;
}
public void setRating(long rating) {
this.rating = rating;
}
}

contentType is the type of data you're sending, so application/json; The default is application/x-www-form-urlencoded; charset=UTF-8.
If you use application/json, you have to use JSON.stringify() in order to send JSON object.
JSON.stringify() turns a javascript object to json text and stores it in a string.
$.ajax({
url: 'https://myrestURL/addRating',
type: 'POST',
dataType: 'json',
data: JSON.stringify({
'id':5,
'name': 'Name',
'rating': '1'
}),
contentType: 'application/json; charset=utf-8',
success: function (result) {
// CallBack(result);
window.alert("Result: " + result);
},
error: function (error) {
window.alert("Error: " + error);
}
});

Related

How can i send a large array to MVC Controller

I am getting an error when sending an array with a length greater than 250 to MVC controller. It works when array length is less than 250 items.
Client Code
function saveVD() {
var arr = [];
$.each($("#tablevd tbody tr"), function () {
arr.push({
invNo: $(this).find('td:eq(0)').html().trim(),
invDate: $(this).find('td:eq(1)').html().trim()
})
})
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: "#Url.Action("Absorb","My")",
data: JSON.stringify({ 'arr': arr }),
success: function (result) {
},
error: function () {
}
})
}
Server Code
public class MyController : Controller
{
[HttpPost]
public JsonResult Absorb(CIVM[] arr)
{
return Json(true, JsonRequestBehavior.AllowGet);
}
}
public class CIVM
{
public string invNo { get; set; }
public DateTime invDate { get; set; }
}
Below config changes may help you
<appSettings>
<add key="aspnet:MaxJsonDeserializerMembers" value="150000" />
</appSettings>

Passing Multiple JSON objects via AJAX to ASP.Net PageMethod

I am trying to pass two JSON Objects to my Page Method via AJAX
I created a class in Code Behind and created a JSON Object Array in javascript.
Following are my two classes and Page Method
public class userModel
{
public string userid { get; set; }
public string Name { get; set; }
}
public class companyModel
{
public string companyid { get; set; }
public string Name { get; set; }
}
[WebMethod]
public static string TestJsonMethod(userModel[] users)
{
return "";
}
And Following is my Javascript
function TestJSON() {
//var JSONObject = { a: [], b };
var obj = {users: []};
var user;
for (var i = 0; i < 3; i++) {
user = {
userid: i.toString(),
Name: "User" + i.toString()
}
obj.users.push(user);
}
var company = {companyid: "4", Name:"TEST COMPANY"};
$.ajax({
url: "bulkconsignments.aspx/TestJsonMethod",
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(obj),
async: false,
cache: false,
success: function (msg) {
alert(msg.d);
}
});
}
Up till this point my code is working fine.
What I want to do is to pass the company object to the Page Method as well like this
[WebMethod]
public static string TestJsonMethod(userModel[] users, companyModel company)
{
return "";
}
You could merge the models into one model.
public class TestJsonModel
{
public UserModel UserModel { get; set; }
public CompanyModel CompanyModel { get; set; }
}
Then action looks like;
[WebMethod]
public static string TestJsonMethod(TestJsonModel model)
Also, Ajax request post data looks like;
data: JSON.stringify({UserModel:obj,CompanyModel:company})
I was trying out different ways of doing it and this one worked.
function TestJSON() {
//var JSONObject = { a: [], b };
var obj = {users: [], company: {}};
var user;
for (var i = 0; i < 3; i++) {
user = {
userid: i.toString(),
Name: "User" + i.toString()
}
obj.users.push(user);
}
var company_ = {companyid: "4", Name:"TEST COMPANY"};
obj.company = company_;
$.ajax({
url: "bulkconsignments.aspx/TestJsonMethod",
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(obj),
async: false,
cache: false,
success: function (msg) {
alert(msg.d);
}
});
}
And the Code behind Page Method remains same.
[WebMethod]
public static string TestJsonMethod(userModel[] users, companyModel company)
{
return "";
}

How to create a nested ajax requests?

I have a WEB API that is working fine. I want to call an action that is a part of my API via Ajax request. It seems that it is easy and I had it working for simple requests. However, I tried to put nested calls and for some reason the data that is passed to the second request gets lost. I was wondering if it is a scope problem or something I did wrong in my code.
Here is the javascript code:
$("#submit_request").click(function () {
var firstName = $("#first_name").val();
var lastName = $("#last_name").val();
var faciltiy = $("#facility").val();
// Collecting all the documents into an array of JSON
var documents = [];
var request = JSON.stringify({
"PatientFirstName": firstName,
"PatientLastName": lastName,
"Facility": faciltiy
});
//the first request is working fine and it has a success state
$.ajax({
url: "http://localhost:64611/api/requests/createRequest",
type: "POST",
dataType: 'json',
contentType: 'application/json',
data: request,
success: function (request_id, state) {
for (var i = 0; i < 5; i++) {
var RequestDocument = {
"RequestID": i,
"DocumentID": i+1,
"StartDate": Date(),
"EndDate": Date()
};
documents.push(RequestDocument);
}
console.log(documents); // it is returning a correct object
console.log(typeof (documents)); // type object
$.ajax({
url: "http://localhost:64611/api/requests/addDocumentsOfARequest/",
type: "post",
datatype: 'json',
contenttype: 'application/json',
data: JSON.stringify(documents), ---> this object should be passed to the api action
success: function (response, state) {
},
error: function (err) {
if (err) {
}
}
});
},
error: function (err) {
if (err) {
}
}
});
});
The definition of my api action is like the following
public async Task<IHttpActionResult> addDocumentsOfARequest(RequestDocument[] documents)
The class RequestDocument is like the following:
public class RequestDocument
{
[Required]
public int RequestID { get; set; }
[Required]
public int DocumentID { get; set; }
[Required]
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
My WebApiConfig is like the following:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "defaultApiRoutes",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { id = #"\d+" } // Only matches if "id" is one or more digits.
);
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
}
}
the parameter 'documents' is empty. Any idea?
Thanks!
Here's my exact working code :
Server
public class GamesController : ApiController
{
// GET api/<controller>
[HttpPost]
public async Task<IHttpActionResult> Post(RequestDocument[] document)
{
var req = await Request.Content.ReadAsStringAsync();
return Ok();
}
}
public class RequestDocument
{
[Required]
public int RequestID { get; set; }
[Required]
public int DocumentID { get; set; }
[Required]
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
JavaScript
var documents = [];
for (var i = 0; i < 5; i++) {
var RequestDocument = {
"RequestID": i,
"DocumentID": i+1,
"StartDate": Date(),
"EndDate": Date()
};
documents.push(RequestDocument);
}
$.ajax({
url: "http://localhost:1757/api/games",
type: "POST",
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(documents),
success: function(a, b) {
alert("Done");
}
});
Result
try this,
$.ajax({
url: "http://localhost:1757/api/games",
type: "POST",
dataType: 'json',
contentType: 'application/json',
data: {
document: documents
},
success: function(a, b) {
alert("Done");
}
});

How to pass json string to webmethod c# ASP.NET

Im trying to stringify a javascript object and then pass the string as a parameter to a WebMethod in Code Behind. I can't get it to work as I get a Internal Server Error of 500 and the stacktrace says that value is missing for parameter.
Here is the javascript code:
var jSon = JSON.stringify(javascriptObject);
// "{"Foretagsnamn":"Avector","BGFarg":"000000","TextColor":"fafafa","FooterFarg":"ffffff","FooterColor":"000000","FooterLinkColor":"050505","FeaturedBorderColor":"","HoverFarg":"12ebeb","RutFarg":"0d0d0d","SelectedRutFarg":"","RutColor":"FFFFFF","LankColor":"","DelaMedSig":"1","PersonalSida":"0","StartpageTitle":"","StartpageDescription":"","GoogleMaps":"<iframe width=\"425\" height=\"350\" frameborder=\"0\" scrolling=\"no\" marginheight=\"0\" marginwidth=\"0\" src=\"https://maps.google.se/maps?f=q&source=embed&hl=sv&geocode=&q=Avector AB&aq=&sll=56.225986,12.870827&sspn=0.076248,0.154324&ie=UTF8&hq=Avector AB&hnear=&t=m&cid=645910733081021950&iwloc=A&ll=56.224594,12.859229&spn=0,0&output=embed\"></iframe><br /><small>Visa större karta</small>","HittaKartaUrl":"http://www.hitta.se/avector ab/ängelholm/hxTP-4v1HG?vad=Avector AB","EniroKartaUrl":"http://kartor.eniro.se/m/aKkhi","Ikoner":"2","Email":"info#avector.com","AdressSida":"1","shadowColor":"ffffff","lineColor":"2b292b","MenuHoverIcon":"Välj bild från server","fontFamily":"Verdana","supportText":"Support Avector","captcha":true,"metaKeywords":"","ShowSupportInFooter":true}"
$.ajax({
type: "POST",
url: "Post/Installningar.aspx/Updatera",
data: jSon,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var resultAsString = result.d;
//_this.parent().siblings('.SavedStatus').html(resultAsString);
if (resultAsString == "1") { // Gick bra att spara.
alert("Uppgifterna är sparade.");
document.location = document.location;
}
else {
$('#StatusText').html("Gick inte att spara uppgifterna.");
}
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
And here Is the webmethod:
[WebMethod]
public static string Updatera(string jSon)
{
It feels like I've tried everything that I've found when searching by google and here on SO.
I've also tried this guide that many refer to: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Any ideas?
First, you need to use:
var jSon = JSON.stringify({obj:javascriptObject});
instead of:
var jSon = JSON.stringify(javascriptObject);
Then your WebMethod would be like:
[WebMethod]
public static string Updatera(aData obj)
{
// logic code
}
Now here aData is your class something like below :
public class aData {
public string Foretagsnamn { get; set; }
public string BGFarg { get; set; }
public string TextColor { get; set; }
public string FooterFarg { get; set; }
public string Email { get; set; }
}
So your final code look like
jQuery:
var jSon = JSON.stringify({ obj:javascriptObject });
$.ajax({
type: "POST",
url: "Post/Installningar.aspx/Updatera",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnErrorCall
});
function OnSuccess(response){
// Do something
}
function OnErrorCall(){
// Do something
}
Code Behind:
public class aData {
public string Foretagsnamn { get; set; }
public string BGFarg { get; set; }
public string TextColor { get; set; }
public string FooterFarg { get; set; }
public string Email { get; set; }
}
[WebMethod]
public static string Updatera(aData obj)
{
// Logic code
}
Use this format for ajax post format :
var jSon = JSON.stringify(javascriptObject);
Your Json Format will be like this :
'{name: "' + name +'" }',
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "Installningar.aspx/Updatera",
data: jSon;
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
Follow this step for complete run your code :
http://www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx

MVC [HttpPost] Method receives null parameter

I'm sending a value through JQuery to an MVC HttpPost action method, but instead it is getting a null value. When I send a plain string it works fine, but when I send an array it gets the null value. Here is the code.
code to send the value
function Submit() {
var QSTR = {
name: "Jhon Smith",
Address: "123 main st.",
OtherData: []
};
QSTR.OtherData.push('Value 1');
QSTR.OtherData.push('Value 2');
$.ajax({
type: 'POST',
url: '/Omni/DoRoutine',
data: JSON.stringify({ obj: 'Reynor here!' }),
// this acctually works
// and at the action method I get the object[]
// with object[0] = 'Reynor here!'
// but when I use the object I really need to send I get null
data: JSON.stringify({ obj: QSTR }), //I get null
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (msg) {
alert('ok');
},
error: function (xhr, status) {
alert(status);
}
});
}
this is the action method code:
[HttpPost]
public ActionResult DoRoutine(object[] obj)
{
return Json(null);
}
What is the solution for this and why is this happening?
thanks
QSTR is a complex type, so you need complex data in your post method.
public class QSTR
{
public string name { get; set; }
public string Address { get; set; }
public object[] OtherData { get; set; }
}
[HttpPost]
public ActionResult DoRoutine(QSTR obj)
{
return Json(null);
}
But if you want receive only array of otherdata you should send only in in your ajax:
$.ajax({
data: JSON.stringify({ obj: QSTR.OtherData }),
// other properties
});

Categories