Losing values in JSON when passing to WEb API Action - json

I have an object (A) with a few properties, one of which is a LIST of abother type (B).
I have a Web API Action that takes in an A object as a parameter.
I am just testing that I can pass this object via JSON son I have a webform with some Javascript on it as follows.......
var tmpData = {
lid: "f8fdb980-ccb8-4a54-9b83-b73dd2d569ca",
aid: "8f6efc68-d747-42a4-b7d4-218951b66a97",
bid: "e9f5e5d2-5d3d-41ac-89dc-7586ec2a5286",
ps: []
};
tmpData['ps'].push({ "cid": "5a664dcc-8281-41f1-b81c-ae49499e12b8", "d": 5, "q": 2 });
tmpData['ps'].push({ "cid": "4e9a30e0-c741-4708-88d7-8db4941c17cc", "d": 10, "q": 2 });
var myJSON = JSON.stringify(tmpData);
//Call the action to get the list in JSON format
url = "http://localhost:64878/home/TakeTestBasketAddItemsRequest";
$.ajax({
url: url,
type: 'POST',
cache: false,
data: myJSON,
success: function (resultantData) {
var s = resultantData;
pResults.innerHTML = s;
}
});
This gets to the action OK and the object has 2 items in the "ps" property.
Howeverm the values in these 2 items are lost and I am left with zeros / uninitialised values.
Whay am I losing the values of the list items?
For clarity - here is my Action also.
[HttpPost]
public ActionResult TakeTestBasketAddItemsRequest(ECodeBasketRequest model)
{
try
{
var sb = new StringBuilder();
sb.AppendLine(String.Format("LocationBridgeId: {0}{1}", model.lid, Environment.NewLine));
sb.AppendLine(String.Format("ApplicationBridgeId: {0}{1}", model.aid, Environment.NewLine));
sb.AppendLine(String.Format("BasketId: {0}{1}", model.bid, Environment.NewLine));
foreach (var p in model.ps)
{
sb.AppendLine(String.Format("CategoryBridgeId: {2} Denomination: {0} Quantity: {1}{3}", p.d, p.q, p.cid, Environment.NewLine));
}
return Content(sb.ToString());
}
catch (Exception ex)
{
return Content(string.Format("Problem: {0}", ex.ToString()));
}
}
As I said, I am just testing at the moment so would love to get to the bottom of this. Thanks in advace,
Ant

Apologies all - but it seems I ommitted the content type....
contentType: "application/json"
It's misleading when some of the object is reconstruucted OK and the rest isn't....but hey ho - It's Friday and it's working..
Well hopefully it will help someone else out.......
So I now find that this works.....
$.ajax({
url: url,
type: 'POST',
cache: false,
**contentType: "application/json",**
data: myJSON,
success: function (resultantData) {
var s = resultantData;
pResults.innerHTML = s;
}

Related

How to pass a collection of <Model> from view to Controller in .net mvc

thanks for taking the time to read my question....
The solution doesn't have to be with ajax ... i need anything to make this work as described....
I need to do the following
Image for the site
if i select private cars from the ad type it shows only the private cars, if i select BMW Make it shows only BMW , and so on for the rest of the search... i did that ..
The problem is when i try to combine multiple searches parameters
example: if i need to show only the private Used cars which are BMW and in specific city and sort the result by price or mileage etc....
I didn't manage to do that ... i tried to wrap the results every time as a list then pass this list by ajax to a controller to do the stuff then retrieve it in a partial View... but i couldn't pass This list (list(Class UserCar))......
I think that if a generous man guided me to do sorting right , it will be same for all search parameters...
This is the view model which contains usercar Model which have all the data i want to retrieve from database
public class VMUserCar
{
public UserCar UserCar { get; set; }
public IEnumerable<UserCar> CarsList { get; set; }
public int? CarsListCount{ get { return CarsList.Count(); } }
}
This is the Index which contains the partial View
<div class="searchDiv">
#Html.Partial("~/Views/Partial_Views/_DisplayAds/_SearchResultDisplay.cshtml")
</div>
This is the partial view which displays all the userCars which displayed in the site image above ( I removed html as possible to minimize distractions)
#model CarSales.Models.CarsForSale.VMUserCar
#foreach (var item in Model.CarsList)
{
#item.Year #item.Make #item.Model #item.Badge #item.BodyStyle
#item.DriveType --&& Other stuff--
}
#*SortBy (in the same view)*#
<script>
$(document).ready(function () {
var SortDD = $('#SortDD');
var searchDiv = $('.searchDiv');
var carsList = '#Html.Raw(Json.Encode(Model.CarsList))';
//var carsList1 = JSON.stringify(carsList);
console.log("List: " + carsList);
SortDD.change(function () {
$.ajax({
//processData: false,
traditional: true,
dataType: 'html',
contentType: 'application/json; charset=utf-8',
data: { list: carsList,searchValue: SortDD.val() },
url: '#Url.Action("SortSearch", "DisplayAds")',
type: 'post',
success: function (response) {
searchDiv.empty();
if (response !== null) {
searchDiv.append(response);
} else {
searchDiv.append("Search returns null from sort DD");
}
},
error: function (ex) {
alert("Error from sort DD: ", ex.statusText);
}
});
});
});
</script>
And this is the controller which will receive the ajax
[HttpPost]
public PartialViewResult SortSearch(string searchValue, IEnumerable<UserCar> list)
{
ViewBag.SortDD = new SelectList(Utilties.GetSortDD(), "Value", "Text", searchValue);
switch (searchValue)
{
case "1":
list = list.OrderByDescending(x => x.AdCreationDate).ToList();
break;
case "2":
list = list.OrderByDescending(x => x.Odometer).ToList();
break;
case "3":
list = list.OrderBy(x => x.Make).ToList();
break;
--& other 10 cases--
var vmUserCar = new VMUserCar() { CarsList = list};
return PartialView("~/Views/Partial_Views/_DisplayAds/_SearchResultDisplay.cshtml", vmUserCar );
} --this is the same partial view which displays all the userCars --
When i run and ajax contains :
contentType: 'application/json; charset=utf-8',
It gives me "Invalid JSON primitive: list1." and doesn't continue to action...
& when i run without it, it goes to action but The list value on the controller is always null..
I tried '#Html.Raw(Json.Encode(Model.CarsList))' alone and value is null always but when i console.log it.... i get json values..
and JSON.stringify(carsList) also null but no values at all when i console log it...
When i changed the list value of controller to IEnumerable list
It retrieves the values as one long string line but i don't know how to convert it to UserCar class
Thanks again for taking the time to read all of that... any help will be much appreciated....
$(document).ready(function () {
function PassThings()
{
var things = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
];
things = JSON.stringify({ 'things': things });
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: $("body").attr("data-project-root") + "Administration/Actions/PassThings",
data: things,
success: function () {
$('#result').html('"PassThings()" successfully called.');
},
failure: function (response) {
$('#result').html(response);
}
});
}
PassThings();
});
For this Controller ::
public void PassThings(List<Thing> things)
{
var t = things;
}
For this ViewModel ::
public class Thing
{
public int Id { get; set; }
public string Color { get; set; }
}
Its must be work, and I recheck this.Would you please recheck this.

Getting JSON Response back from MVC Controller from Ajax call

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

How to send multiple parameters from kendo data source read operation to WebApi controller

I have the following scenario: I have a kendo.dataSource which is populated via read request to a WebApi Controller. In addition to the read, I am sending a couple of parameters, which then I use in my controller to do some server logic. I was able to send as many simple parameters as I want via the parameterMap property of the transport function. Till now it was a simple get request. However now I need to send additional json object to the controller as a parameter. I read that I have to transform the Get request to Post and put the Json onto the body of the request but I don't know how to do it.
The code that I have so far:
var gridDataSource = new kendo.data.DataSource({
type: 'odata-v4',
transport: {
read: {
url: wave.alarmsAndEvents.api('api/alarmsAndEventsSearch/post'),
type: "POST",
data: {
SearchModel: JSON.stringify(vm.searchModel)
},
contentType: 'application/json; charset=utf-8',
},
parameterMap: function (data, operation) {
if (operation === "read") {
data.startDate = kendo.toString(vm.selectedTimeInterval.start, "G");
data.endDate = kendo.toString(vm.selectedTimeInterval.end, "G");
data.alarmsToDisplay = vm.maxRecords;
}
return kendo.stringify(data);
}
},
pageSize: vm.maxRecords,
error: function (e) {
alert(e.xhr.responseText);
}
});
The SearchModel is the thing that I want to send as JSon. The rest are simple DateTime and int parameters.
My controller:
[HttpPost]
public IQueryable<AlarmsSearchViewModel> Post(DateTime startDate, DateTime endDate, int alarmsToDisplay, [FromBody]JToken jsonbody)
{
....
return something;
}
I end up with Not Found 404, but I am pretty sure that I have messed up the parameters. And from the Network window I can see that the json object is not sent at all. Any help will be much appreciated!

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 post json data with extJS

I'm a bit of a newb with both extJS and json. What is the most painless route to POSTing json data using extJS? I'm not really interested any GUI features, just using the framework to send some sample data.
Ext.Ajax.request({
url: 'foo.php', // where you wanna post
success: passFn, // function called on success
failure: failFn,
params: { foo: 'bar' } // your json data
});
The following will identify as 'POST' request
Ext.Ajax.request({
url: 'foo.php', // where you wanna post
success: passFn, // function called on success
failure: failFn,
jsonData: { foo: 'bar' } // your json data
});
The following will identify as 'GET' request
Ext.Ajax.request({
url: 'foo.php', // where you wanna make the get request
success: passFn, // function called on success
failure: failFn,
params: { foo: 'bar' } // your json data
});
Just to add my two cents:
//
//Encoding to JSON:
//
var myObj = {
visit: "http://thecodeabode.blogspot.com/"
};
var jsonStr = Ext.encode(myObj);
//
// Decoding from JSON
//
var myObjCopy = Ext.decode(jsonStr);
document.location.href = myObj.visit;
The examples posted here show the basic idea. For complete details on all configurable options see the Ext.Ajax docs.
Code Snippet:
Ext.Ajax.request({
url: "https://reqres.in/api/users",
success: function (response) {
Ext.Msg.alert("success", response.responseText);
},
failure: function () {
Ext.Msg.alert("failure", "failed to load")
},
params: {
"name": "morpheus",
"job": "leader"
}
});
Fiddle: https://fiddle.sencha.com/#view/editor&fiddle/28h1