I am using the Map() functionality in ES6 to create a list of keypair values, making an ID number to a boolean value. I want to pass this Javascript object to an MVC 4 Controller.
Here's my Javascript:
var bankHolidays = new Map();
$('.bank-holiday-switch').each(function () {
var id = $(this).attr('id');
var isChecked = $(this).is(':checked');
bankHolidays.set(id, isChecked);
});
$.ajax({
url: '/AdminPanel/Settings/SaveBankHolidays',
type: 'POST',
data: { bankHolidays: bankHolidays },
success: function (result) {
alert("Success");
}
});
I can console.log() the map object and see that it's being created as intended. However, when I pass it to this MVC Controller:
[HttpPost]
public JsonResult SaveBankHolidays(Dictionary<int, bool> bankHolidays)
{
// DO stuff
}
..no error is thrown, but it just says the bankHolidays dictionary has 0 values in it. I can call other Actions in that Controller without issue. I have tried many different combinations of Dictionary<string, bool> to no avail.
Can somebody tell me what I am doing wrong?
In a http negotiation, xhr in this case, we must send strings, so you need some string representation of Map(), the best option, in my opinion, is to use a JSON stringify in some way, because the parse of JSON have a broad support among server side code:
var bankHolidays = new Map();
bankHolidays.set(1, 2);
bankHolidays.set(3, 4);
var result = JSON.stringify([...bankHolidays]);
console.log(result)
In your code something like :
$.ajax({
url: '/AdminPanel/Settings/SaveBankHolidays',
type: 'POST',
data: JSON.stringify([...bankHolidays]),
success: function (result) {
alert("Success");
}
});
In backend you have to parse the response, see this.
Related
I use an AJAX request to get the data from the backend when user select an option from a dropdown menu.
$('#adSpace').change(function () {
var sel_opt = $(this).val();
alert(sel_opt);
var location = null;
var width = null;
var height = null;
$.ajax({
type: "GET",
dataType: 'json',
url: "advertisements-controller.php",
data: {
action: "getDimension",
location: sel_opt
},
success: function (response) {
location = response.banner_location;
alert(location);
},
error: function (xhr) {
alert("error");
}
});
});
Now i'm getting the data from backend in JSON format like below:
[{"banner_location":"category_group_sidebar","banner_width":250,"banner_height":225}]
I want to access the values of banner_location, banner_width, banner_height by assigning those to javascript variables but I'm failing to do it.
Any ideas?
Use this
location = response[0].banner_location;
Your response comes in the form of an array: [...]. That means you can access the first array item by using the index. Also if there are multiple objects you can iterate response with forEach or jQuery's each($(response).each).
response[0].banner_location
response is an array of json. In order to access the json you need to firsr access the index of the array which is done by array[indexNumber] then the key of the json.
In your case it will be response[0].banner_location
i am trying to parse json datalist in ajax success bt it couldnot work. i have passed object containing list of data using json from controller to view,i help to parse json object in ajax success. i have attached my code below.
//return json object from controller
PurchaseDetails pd = new PurchaseDetails();
foreach (DataRow dr in dt.Rows)
{
pd.serialList.Add(new SerialInfo {
Machine_serial_no = dr[0].ToString(), macAddress = dr[1].ToString(), isMacPresent = _TD1.CheckMac(machineTypes_MTId),brandName=obj.brandName,machineName=obj.machineName,MachineModel=obj.MachineModel,modelId=modelId,machineId=obj.machineId,brandId=obj.brandId});
// pd.macaddressList.Add(new MacAddressInfo { MacAddress = dr[1].ToString() });
}
}
}
return Json(new {pd}, JsonRequestBehavior.AllowGet);
return Json(new {pd}, JsonRequestBehavior.AllowGet);
// my ajax code
$.ajax({
url: "/Import/ImportPurchase",
type: "POST",
data: function () {
var data = new FormData();
data.append("file", jQuery("#file").get(0).files[0]);
data.append("machineTypes_MTId", jQuery('#machineTypes_MTId').val());
data.append("modelId", jQuery('#searchValue').val());
data.append("modelName", jQuery('#searchid').val());
return data;
}(),
dataType:"JSON",
contentType: false,
processData: false,
success: function (data) {
alert(data.Machine_serial_no)
Your controller method is returning
return Json(new { serialObj = pd}, JsonRequestBehavior.AllowGet);
which is an object containing a name serialObj
So in the ajax success call back, you would need to access it using
success: function (data) {
var PurchaseDetails = data.serialObj;
Since PurchaseDetails contains a collection named serialList which is a collection of SerialInfo, then to access the value of the first Machine_serial_no, it would be
var serialNo = data.serialObj.serialList[0].Machine_serial_no;
However it would be easier to just use
return Json(pd, JsonRequestBehavior.AllowGet);
If you then want to access each Machine_serial_no property in the collection, use
success: function (data) {
$.each(data.serialList, function(index, item) {
var serialNo = item.Machine_serial_no;
you can use jQuery.parseJSON() to parse ajax response to JSON.
but seeing from your code, seems the response should already be in JSON because dataType parameter is already set to "JSON".
try this:
remove "()" after the ending bracket of function in "data" parameter.
try to console.log(data) and look at the response from your browser console,
the response might not be a valid json string.
If you are looking for convert js array to JSON then just use JSON.stringify() function. This will convert your JS variable data value to JSON format.
You can more find here.
I'm writing a user interface in javascript, it will take data from the HTML and pass it through an API using javascript. I am trying to take the data and pass it to a function without writing a bunch of if statements. However some actions have the actions are the same names in other controllers. So I have a nested namespace, now I can't get to the nested function. Hopefully someone can help.
Everything before this works fine.
var apiHandler = {
user: {
login: function(){
console.log("test");
}
}
};
function callAPI(apiObject){
//console.log(apiObject);
var apiData = JSON.stringify(apiObject);
$.ajax({
type: "POST",
url: 'https://dev.tragicstudios.com/clients/trego/api/index.php',
data: {'enc_request':apiData},
dataType: 'json',
success: function(data){
var apiFunction = apiObject.controller+"."+apiObject.action;
console.log(apiFunction);
apiHandler["user.login"]();
return data;
}
});
}
Just use the controller and action part as separate keys, instead of combining them:
apiHandler[apiObject.controller][apiObject.action]();
For this specific example, instead of:
apiHandler["user.login"]();
Try
apiHandler["user"]["login"]();
I am building an ASP.NET MVC application It currently has a button that once clicked does an Ajax call to the controller as so:
function getData() {
$.ajax({
url: "/Home/GetData/",
type: "POST",
contentType: 'application/json',
success: function (data){
//need to do stuff here
}
});
}
The controller then initializes a class, converts it to XML and then converts that to the following dictionary (There is a reason for this):
public ActionResult GetData()
{
List<People> peeps = GetPeeps();
string xml = ToXml(peeps);
Dictionary<string,List<string>> stuff = ToDictionary(xml);
return Json(stuff);
}
I would like to be able to 'Do stuff' with this data client side with javascript.
The APIs I have to work with Server side return XML data.
The APIs I have to work with Client side require string arrays. (Hence the conversions)
Is there a way to use the dictionary i've defined above client side? Could someone perhaps expand from this (if possible) to add to the ajax call a small method that prints the contents of the dictionary to a message box? just to give me a starting point from how to use the dictionary in javascript.
Thanks in advance
You can try in the ajax call as follow:
function getData() {
$.ajax({
url: "/Home/GetData/",
type: "POST",
contentType: 'application/json',
success: function (data){
console.log(data.key1); // value for key1
//or to list all values
for(var key in data){
console.log(data[key]);
}
}
});
}
Controller (for explanation purposes):
public ActionResult GetData()
{
//List<People> peeps = GetPeeps();
//string xml = ToXml(peeps);
//Dictionary<string,List<string>> stuff = ToDictionary(xml);
Dictionary<string,List<string>> stuff = new Dictionary<string, List<string>>
{
{"key1", new List<string> {"a", "b", "c"}},
{"key2", new List<string> {"d", "e", "f"}},
};
return Json(stuff);
}
I hope this is clear enough. Let me know how you go :)
I have this controller method:
public JsonResult List(int number) {
var list = new Dictionary <int, string> ();
list.Add(1, "one");
list.Add(2, "two");
list.Add(3, "three");
var q = (from h in list where h.Key == number select new {
key = h.Key,
value = h.Value
});
return Json(list);
}
On the client side, have this jQuery script:
$("#radio1").click(function() {
$.ajax({
url: "/Home/List",
dataType: "json",
data: {
number: '1'
},
success: function(data) {
alert(data)
},
error: function(xhr) {
alert(xhr.status)
}
});
});
I always get an error code 500. What's the problem?
Thank you
If you saw the actual response, it would probably say
This request has been blocked because
sensitive information could be
disclosed to third party web sites
when this is used in a GET request. To
allow GET requests, set
JsonRequestBehavior to AllowGet.
You'll need to use the overloaded Json constructor to include a JsonRequestBehavior of JsonRequestBehavior.AllowGet such as:
return Json(list, JsonRequestBehavior.AllowGet);
Here's how it looks in your example code (note this also changes your ints to strings or else you'd get another error).
public JsonResult List(int number) {
var list = new Dictionary<string, string>();
list.Add("1", "one");
list.Add("2", "two");
list.Add("3", "three");
var q = (from h in list
where h.Key == number.ToString()
select new {
key = h.Key,
value = h.Value
});
return Json(list, JsonRequestBehavior.AllowGet);
}
While JustinStolle's answer solves your problem, I would pay attention to the error provided from the framework. Unless you have a good reason to want to send your data with the GET method, you should aim to send it with the POST method.
The thing is, when you use the GET method, your parameters gets added to your request url instead of added to the headers/body of your request. This might seem like a tiny difference, but the error hints why it's important. Proxy servers and other potential servers between the sender and the receiver are prone to logging the request url and often ignore the headers and/or body of the request. This information is also often regarded as non important/secret so any data exposed in the url is much less secure by default.
The best practice is then to send your data with the POST method so your data is added to the body instead of the url. Luckily this is easily changed, especially since you're using jquery. You can either use the $.post wrapper or add type: "POST" to your parameters:
$.ajax({
url: "/Home/List",
type: "POST",
dataType: "json",
data: { number: '1' },
success: function (data) { alert(data) },
error: function (xhr) { alert(xhr.status) }
});