URL parameters on javascript - javascript

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(',')]

Related

Pass array values from JavaScript to my MVC C# application

I would like to pass array values from javascript to my C#.
Currently I am getting GUID null in C#. Not sure where I am doing wrong.
When I check developer tool, I have values
http://localhost/mvc/CheckData?GUID[]=C71F952E-ED74-4138-8061-4B50B9EF6463&ColumnVal=1&RowVal=1
I would like to receive this GUID value in my C# code.
JavaScript
function CheckData(obj) {
$.ajax({
data: {GUID:eArray, ColumnVal: $('#DisColumn').val(), RowVal: $('#DisRow').val()},
url: "/mvc/CheckData",
cache: false,
success: function (result) {
....
}
});
}
C# backend code to receive values from front-end.
public ActionResult CheckData()
{
var GUID = HttpContext.Request["GUID"];
int columnVal = Convert.ToInt32(HttpContext.Request["ColumnVal"]);
int rowVal = Convert.ToInt32(HttpContext.Request["RowVal"]);
string result = (Services.CheckDataRecords(rowVal, columnVal,GUID)) ? "true" : "false";
return Content(result);
}
Currently, I am getting null when it hits to C# method var GUID = HttpContext.Request["GUID"];.
I can see array value in front-end. But it is somehow not passing that value.
HttpContext.Request represents the request, and to access query data, you will need to do something like this: HttpContext.Request.Query["GUID"].
A more straightforward approach is to let ASP.NET do the work for you is just turn your C# backend to this:
[HttpGet("CheckData")] //change the route based on your code
public ActionResult CheckData([FromQuery] Guid[] guid, int columnVal, int rowVal)
{
var GUIDs = guid;
int column = columnVal;
int row = rowVal;
.....//your code
}

Pasing Javascript result to View

I got a Question, I'm really new in working with Asp.net.
I got a Javascript where I woult like to pass Data to my Controller.
<script type="text/javascript">
$("#SearchButton").on("click", function () {
var $sucheMoped = [];
$("#tab_logic tbody tr")
.each(function () {
var $Item = $(this);
var suchfeld = $Item.find("td > input[name='Suchfeld']").val();
var schluessel = $Item.find("td > select[name='Suchschluessel'] > option:selected").val();
alert(suchfeld + "&&&" + schluessel);
$sucheMoped.push({
Suchfeld: suchfeld,
Suchschluesseltyp: schluessel
});
});
window.open('#Url.Action("MainView","MainView")?SuchObject='+$sucheMoped);
})
</script>
I just would like to pass the "sucheMoped" from my javaScript to my Controller.
My Controller is just expecting a IEnumarable of Objects with Properties Suchfeld and Suchschluesseltyp.
Anyone an idea?
Thanks Guys.
First of all, you need to change the way you invoke the controller action. You should stringify the array using the JSON.stringify() method.
So, this should look like this:
window.open('#Url.Action("MainView","MainView")?SuchObject='+JSON.stringify($sucheMoped));
Then, you need to create a custom model binder to bind your array with the action parameter. This is a simple array model binder for demonstration purposes only, it doesn't take into account failures or whatever, but it works in this scenario, passing the correct data, so please modify it to fit your needs.
public class ArrayModelBinder: DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var rawArray = controllerContext.HttpContext.Request.QueryString["SuchObject"];
var array = JsonConvert.DeserializeObject<IEnumerable<MyObject>>(rawArray);
return array;
}
}
What I do here, is to get the query string submitted through the URL, convert it with JsonConvert.Deserialize<T> method and return it.
You simply need to decorate your parameter in the controller's action with the custom model binder, like this:
[HttpGet]
public ActionResult Search([ModelBinder(typeof(ArrayModelBinder))]IEnumerable<MyObject> SuchObject)
{
return View(SuchObject);
}
Edit
window.open is useful if you want to open a new browser window. You could use it to open a new tab as well.
In order to navigate to another location without opening a new tab or window, use the window.location property like the following:
window.location = '#Url.Action("Search", "Home")?SuchObject=' + JSON.stringify(array);
If you use the jQuery.ajax method, you can pass complex objects as data parameter.
$.ajax({
url: '#Url.Action("MainView", "MainView")',
type: 'GET',
data: { 'SuchObject': $sucheMoped },
success: function (htmlContent) {
// write content to new window (from http://stackoverflow.com/a/23379892/1450855)
var w = window.open('about:blank', 'windowname');
w.document.write(htmlContent);
w.document.close();
}
});
You can use jquery library $.getScript to call the action method in your controller and the return javascriptResult type in your action.
$.getScript("Home","Display")
// Home Controller
private JavaScriptResult Display()
{
string message = "alert('Hello World');";
return new JavaScriptResult { Script = message };
}

pass collection of objects through http post in angular js

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)
{
}

ASP Web Pages Razor using AJAX to return array from Database

I'm working with ASP for my coursework and I am using Razor Web Pages to do an application. Now, I would like some help with retrieving information from the SQL database.
As it stands I make an ajax call like this:
$.ajax({
type: "POST",
url: "/timetabler/Includes/ajaxModulesByUserId",
data: { id: UserId },
success: function (data) {
alert(data);
if (data == "ERROR") {
alert("We are unable to store the theme you have selected, therefore the change will not be permanent.");
}
}
});
This quite simply calls ajaxModulesByUserId.cshtml passing a userID of like 1. Now this calls the file fantastically.
Now what I'm trying to do in my CSHTML is take the requested ID, then use my C# function:
public IEnumerable<dynamic> getAllQuery(string query)
{
return _db.Query(query);
}
To execute my query.
Now I call it in my Razor code like this:
string input = "";
input = Request["id"];
var arr = new List<string>();
if (!string.IsNullOrEmpty(input))
{
// Add new sheet to database
using (var repo = new initDatabase("SQLServerConnectionString"))
{
foreach (var row in repo.getAllQuery("SELECT * FROM Module WHERE userID = " + input))
{
arr.Add(""+row.moduleCode+","+row.moduleTitle+"");
}
#session.Serialize(arr);
}
}
So I return the rows from the database and put them into an array, now my problem is, getting those values to the javascript.
As it stands I'm using a trick I read from here Stackoverflow, by using a function like this:
public static string Serialize(object o)
{
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(o);
}
This will actually let me see the values in Javascript, but I'm getting stuck as I end up with values like this:
How can I receive a clean array? and possibly even return ALL the rows from the database as I've had to do a messy way of passing the code and title in 1 array field but separated by a comma.
Would really appreciate it if you could help me get my output correct.
Thanks
The Web Pages framework includes a Json helper which can take your data and return it as JSON.
if (!Request["id"].IsEmpty())
{
using (var repo = new initDatabase("SQLServerConnectionString"))
{
var data = repo.getAllQuery("SELECT * FROM Module WHERE userID = #0", Request["id"])
Json.Write(data, Response.Output);
}
}

Controller Action parameter not properly populated from AJAX POST

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

Categories

Resources