I have to make a json call to home controller where I need to pass multiple arrays.
var assetids = new Array(N);
var faultTimes = new Array(N);
var messages = new Array(N);
var curtailments = new Array(N);
//populate above arrays with values then make a JSON call
$.getJSON('Home/AcknowledgeMany', {
assetid: assetids,
loggedBy: $("#UserName").text(),
faultTime: faultTimes,
message: messages,
curtailment: curtailments
}, function (result) {
alert(result);
}
The homecontroller has following action result
public string AcknowledgeMany(int[] assetId, string loggedBy, string[] faultTime, string[] message, string[] curtailment)
{
return("Acknowledged");
}
I receive null values for all the arrays when I make this call. Can someone help me passing arrays.
Try setting the traditional flag
For detail help see this question
Related
I have a function that after adding items in a for loop calls the controller through the action URL sending the arr parameter (array), I see that it sends the data but null appears in the controller parameter. I wanted to know what could be wrong?
Javscript Function
function Submit() {
QRCodeval.forEach((code) => arr.push(code.innerHTML));
window.location.href = "#Url.Action("ReceivedFromBarCode","PurchaseOrder")?" +arr;
}
Link generated by the controller:
http://localhost:56978/PurchaseOrder/ReceivedFromBarCode?JJJKP,RRPRQ,PPLQR
Controller where I get null in the arr parameter.
public async Task<ActionResult> ReceivedFromBarCode(string[] arr)
{
return View();
}
The MVC model binder expects arrays to be passed in the following format: arr=value1&arr=value2&...
You can use map() and join() to create the correct format. But you'll also need to encode the values since they are parameters in a URL. encodeURIComponent can help with that:
let urlParams = array.map((val) => {
return `arr=${encodeURIComponent(val)}`
}).join('&');
window.location.href = "#Url.Action("ReceivedFromBarCode","PurchaseOrder")?"
+ urlParams;
And append the urlParams to your URL. Example output in snippet below:
let array = ["value1", "http://example.com?x=1", "<script>alert('')</sctipt>"];
let urlParams = array.map((val) => {
return `arr=${encodeURIComponent(val)}`
}).join('&');
console.log(urlParams);
I´m making a call using javascript and I would like to send an array:
var selected = [];
selected=getAllEnginesIdsSelected();
console.log("selected: "+selected);
$.getJSON('/call/' + selected,
function(myList) {
The funcion that I use in Javascript to retrieve array is:
function getAllEnginesIdsSelected() {
var selected = [];
$("input:checkbox[id^='engine_']:checked").each(function(){
var ele=$(this)[0].id;
selected.push(ele);
});
return selected;
}
Console.log retrieves selected: 2,5
In MVC Controller I have
#RequestMapping(method = RequestMethod.GET, value = "/call/{selected}")
public List<List<myList>> myCall(#RequestParam(value="selected[]") String[] selected){
I gives an error. I don´t want to use AJAX. This is posible to send?
selected is an array, which you are joining to a string in the URL. Try something like $.getJSON('/call/?selected=[' + selected.join(',')]
I have pass a collection of objects through http post in angular js.
The code is as follows:
$scope.selectedContent = function () {
var contents = $filter('filter')($scope.data.ContentId, { Selected: true }); // I could able to get all the selected objects here, No problem with it
var jsonData = angular.toJson(contents); //It is not able to convert to Json if there are more than 5 records
var promise = $http.post('/webapi/cmsApi/CmsPublishApprovedContent?jsonData=' + jsonData, {});
promise.success(function () {
window.location.reload();
});
[ReferrerFilterAttribute]
[HttpPost]
[System.Web.Http.ActionName("CmsPublishApprovedContent")]
public void CmsPublishApprovedContent(string jsonData)
{
var contents = JsonConvert.DeserializeObject<List<ContentNodeInWorkFlow>>(jsonData);
foreach (var content in contents)
{
_contentService.PublishContent(content.ContentId, userId);
}
}
}
The above code works fine if there are 5 records or less. If there are more records, I could able to get all the selected record
objects in the variable 'contents'. But the problem is occuring when converting to Json for all those objects. I
have about 500 records to pass through. How can do I it?
There is no specific reason to convert to JSON data. I just need to extract the ids of all the selected items. I have modified the above code as below:
$scope.selectedContent = function () {
var contents = $filter('filter')($scope.data, { Selected: true });
var abc = [];
angular.forEach(contents, function(content)
{
abc.push(content.ContentId); // got all the ids in the array now
});
var promise = $http.post('/webapi/cmsApi/CmsPublishApprovedContent' ,{contents : abc});
promise.success(function () {
window.location.reload();
});
}
I have just took an array and pushed all the content ids into it. I could able to see all the ids in the array now. I tried to pass the array as above.
How to retrieve those array in the code behind.
[ReferrerFilterAttribute]
[HttpPost]
[System.Web.Http.ActionName("CmsPublishApprovedContent")]
public void CmsPublishApprovedContent(int[] abc)
{}
I do not see any values obtained under int[] abc. What will be the datatype for the parameter in the method call above.
You need second argument of $http.post method. You have to send such data by POST requests, not in query of url. You can put some data into body of the post request.
You need this:
var postBodyWithHugeAmountOFData = {data: [1,2,3,4,5...500]};
$http.post(url, postBodyWithHugeAmountOFData).success(function () {});
Also, you must be ready to handle this request in your backend.
is there any specific reason u want to pass this data as a JSON?.
if u r using Web API in that case u can pass the object as it is but only make sure that collection in web API method contains all the property in javascript collection
Thank you for all your posts. It's working fine without converting to Json. The code is as below.
$scope.selectedContent = function () {
var contents = $filter('filter')($scope.data, { Selected: true });
var promise = $http.post('/webapi/cmsApi/CmsPublishApprovedContent' ,contents);
promise.success(function () {
window.location.reload();
});
}
and the signature would be
public void CmsPublishApprovedContent(List<ContentNodeInWorkFlow> abc)
{
}
I'm performing an AJAX call and I want the Controller Action (using HttpPost) to accept a parameter of IEnumerable<PercentageViewModel> percentages
where PercentageViewModel is:
public class PercentageViewModel
{
public int Id { get; set; }
public string Percentage { get; set; }
}
The populated data structure on the Action has 2 items in the collection but each item is filled with default values (0 and null). Here is the data as it appears in Chrome Network Headers - when I click on the AJAX Post XHR call
percentages[0][Id]:7
percentages[0][Percentage]:26.1
percentages[1][Id]:8
percentages[1][Percentage]:20.3
Here is the JS where I am populating the params variable that will be sent using the AJAX Post call.
var params = {};
var dict = [];
for (var idx in data) {
var item = {
Id: idx,
Percentage: data[idx]
};
dict.push(item);
}
params['percentages'] = dict;
where the data variable has data like this (when written to Chrome console):
Object {7: "26.1", 8: "20.3"}
How can I construct the data in JS so the data structure in the Action is populated properly?
Full disclosure: this is a rephrasing of a question I asked yesterday - just as a more targeted question.
This was the answer that allow the server side data structure to be populated properly
var i = 0;
for (var idx in data) {
params['percentages[' + i + '].Id'] = data[idx].Id;
params['percentages[' + i + '].Percentage'] = data[idx].Percentage;
i++;
}
I have two modules that I want to connect by navigating from one to the other. Since there are going several parameters to be passed, I want to use query string. Is there a way to use the built-in router to navigate to a module and have my object arguments being passed like
var params = {
param1: "parameter",
param2: "anotherparameter"
}
router.navigate("theothermodule", params);
or do I have to manually parametrize the object into the url string and pass it to router.navigate like
router.navigate("theothermodule?" + $.param(params));
Another solution would be :
var params = {
param1: "parameter",
param2: "anotherparameter"
}
//notes : this object can contain arrays like knockout observable()
//or observableArray();
1.- create the object (params) in shell.js and map it to your route definition like
bellow :
{ route: 'routestr/:id', moduleId: 'viewmodels/adir/mymodul', title: 'je suis',
hash: '#routestr', nav:3, routobj: params }
2.- you could update, even add new members to your object from anywhere before calling this route, by hacking the object from the route.
var myrouteconfig = router.activeInstruction().config;
myrouteconfig.param2 = newvalue;
myrouteconfig.newdlyParam = value;
router.navigate("#routestr/" + id);
3.- Then, in the receipt module :
var activate = function (id) {
//var myid = parseInt(id); //noelem rubriq
var myrouteconfig = router.activeInstruction().config;
var mycallobject = myrouteconfig.params; //your object params
var valparam2 = mycallobject.param2; // your param2 last value
......
}
You have to manually parametrize the object into the url string and map in router.activate (http://durandaljs.com/documentation/Using-The-Router/).
However you can share data with Events(http://durandaljs.com/documentation/Leveraging-Publish-Subscribe/) or Activation Data property in Composition binding(http://durandaljs.com/documentation/Using-Composition/).