Array Passed to Controller Received as NULL - c#

I'm using $.post() to post an array of integer values to my controller.
Here's how I construct my array:
var ratings = [];
$('#ratings input[name=newReviewRatings]').each(function () {
ratings.push($(this).val());
});
Here's how I'm posting it to the controller:
$.post('#Url.Action("CreateReview", "Provider")',
{
id: providerId,
ratings: ratings,
comment: comment
});
Here's the form data that gets posted:
{id=437baf29-4196-4966-88de-a8fde87ef68d&ratings%5b%5d=1&ratings%5b%5d=2&ratings%5b%5d=3&ratings%5b%5d=4&ratings%5b%5d=5&comment=Comments}
And here's my controller signature:
public ActionResult CreateReview(Guid id, int[] ratings, string comment)
{
// ....
}
That seems like that should be right, but ratings is always null. Can anyone see what I'm missing?
I also tried string[] ratings and got the same result. I also saw a suggestion to pass the array using JSON.stringify(ratings) but that didn't seem to help either.

In adition to converting the post data to json, you can also set the traditional param to true. This will cause jQuery to use the correct post format for MVC.
jQuery.ajaxSettings.traditional = true;
$.post('#Url.Action("CreateReview", "Home")',
{
id: 'GUID STRING HERE',
ratings: [1, 2, 3],
comment: 'adfef'
});

Try to specify contentType like this:
$.ajax({
url:url,
type:"POST",
data:data,
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(){
...
}
})

Related

Why ajax call doesn't bind to int[] with jquery .post()

Here is my ajax call:
var idsOfRecordsToBeDeleted = [];
$("#container :checked").each(
function (index) {
idsOfRecordsToBeDeleted.push($(this).attr('id'));
});
var parametersList = { param1: 123456, param2: idsOfRecordsToBeDeleted };
$.post("/Home/Index", parametersList, function (returnedData) {
alert(returnedData);
});
and there is my controller:
[Authorize]
[HttpPost]
public virtual ActionResult Index( int param1, int[] param2)
{
return null;
}
and param1 is OKAY but param2 is always null. Can you help?
You can turn traditional on for your jQuery post to allow for shallow array serialization.
jQuery.ajaxSettings.traditional = true;
var parametersList = { param1: 123456, param2: [1, 2, 3, 4] };
$.post("/Home/Index", parametersList, function (returnedData) {
alert(returnedData);
});
If you would like to apply traditional mode to only this post, you can add it with $.ajax.
var parametersList = { param1: 123456, param2: [1, 2, 3, 4] };
$.ajax({
url: "/Home/Index",
type: 'POST',
data: parametersList
traditional: true
});
Since jQuery 1.8, ajax calls will recursively serialize all objects by defaulting the traditional flag to false.
As a result, deep objects end up getting serialized into a string that represents this object structure:
param2[]=1&param2[]=2&param2[]=3&param2[]=4&=param2[]=5
ASP.NET MVC doesn't know how to handle this format. By setting traditional to true, we preserve the structure that ASP.NET MVC expects:
param2=1&param2=2&param2=3&param2=4&param2=5
EDIT:
Based on how you are building your array (attr returns a string), you will end up with an array of strings, not numbers, meaning that MVC will not deserialize your array.
You can confirm the type by inspecting the first element of idsOfRecordsToBeDeleted.
typeof(idsOfRecordsToBeDeleted[0])
Update your controller method to the following signature:
public virtual ActionResult Index( int param1, string[] param2)
Serialize the array to a string, then deserialize it on the server.
Client:
param2: [1, 2, 3, 4].join(',');
Server (Change param2 type to string instead of int[]):
int[] param2Parsed = param2.Split(',').Select(s => int.Parse(s)).ToArray();

Javascript function call to c# method to get array of integers for datatables.net column order

I must profess that i am not very good with Javascript.
I am creating a table using datatables.net
The datatable is populated using a call to a generic handler that will then call the database (in c#) to get values. This is working.
What i'd like to do is use the column re-order functionality. Setting the order is by an array of integers. I'd like those values to be stored in the database and then assign use it. I haven't thought about the saving columns order part first as i want to get the "get" process working first.
In a normal world, the code to set the column re-order is by coding it into the datatables functionlity like:
<script>
$(function () {
var columnOrder = [4, 3, 2, 1, 0, 5];
$("#<%=DT.ClientID%>").dataTable({
dom: 'Rlfrtip',
colReorder: {
order: columnOrder
},
"bProcessing": true,
"bServerSide": true,
"bFilter": false, //Hide the search box
"sPaginationType": "full_numbers",
"sAjaxSource": "../DataHandler/Data.ashx",
So what I'd like to do is to populate the "columnOrder" with values from the database.
i tried using a webmethod and then getting that value by $.ajax({ + Post. This went to my c# code behind method on the default.aspx but returned an empty object. It also seems to populate the datatable first before going into the webmethod so the timing of the call is not correct as well.
QUESTION: I'm scratching my head if I am over-complicating this. All i want is the return an array of integers from a c# server-side method to a javascript variable. Then use this variable to set the order of the column.
Any suggestion on how i can just get an array of integers from c# into a variable is basically what i'd need to get started.
thanks!
All i want is the return an array of integers from a c# server-side method to a javascript variable.
I have a method that return an array of integers, not really an array but it works like one in javascript.
The method is below
[WebMethod]
public static List<int> getAdd_Zip(int ZIP_ID)
{
try
{
BusinessContacts objContacts = new BusinessContacts();
DataTable dtInf = objContacts.getAdd_Zip(ZIP_ID);
List<int> lRes = new List<int>();
if (dtInf.Rows.Count > 0)
{
lRes.Add(Convert.ToInt32(dtInf.Rows[0]["COU_ID"]));
lRes.Add(Convert.ToInt32(dtInf.Rows[0]["STE_ID"]));
lRes.Add(Convert.ToInt32(dtInf.Rows[0]["MUN_ID"]));
}
return lRes;
}
catch (Exception ex)
{
throw ex;
}
}
Note that the method returns a List of integer, I declare a datatable, then I fill that table with another method (this not important), then, I fill the List with 3 values.
So now, I have the next method on javascript
function wsGetAdd_Zip(ZIP_ID) {
var AddZips = new Array();
var params = new Object();
params.ZIP_ID = ZIP_ID;
params = JSON.stringify(params);
$.ajax({
type: "POST",
url: "Contactos.aspx/getAdd_Zip",
data: params,
contentType: "application/json; charset=utf-8",
async: false,
success: function (result) {
AddZips = result.d;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + ": " + XMLHttpRequest.responseText);
}
});
return AddZips;
}
That method returns the array of integers.
I hope this helps you.

C# method to return two values from SQL Query, then get via jquery ajax call

UPDATE: This code now works! Between the answer below and my dev who emailed me from Romania, I got it sorted out.
[Method]
public object ConvDetails(string SENDERNAME, string VIEWURL)
{
{
var list = new List<object>();
new Command("select top 1 o.name [SENDERNAME], view_url [VIEWURL] from MESSAGE m join OPR_SECD o on UPDATED_BY = O.RECNUM where VIEW_URL like 'conversation.aspx%' and DELIVER_TO in (select OPR_INITIAL from OPR_SECD where recnum = #CURRENT_USER_ID) order by m.RECNUM desc")
.AddInt("CURRENT_USER_ID", Common.UserID)
.Each(R => list.Add(new
{
VIEWURL = R.GetString("VIEWURL"),
SENDERNAME = R.GetString("SENDERNAME")
}));
return list;
};
}
Here's my ajax call to get the two strings from my method:
convDetails: function() {
$.ajax({
url: BASE_URL + "pages/services/messages.ashx?method=convdetails",
dataType: "json",
async: true,
data: {},
success: function(data) {
$("a.new-message-alert").attr("href", '' + data[0].VIEWURL);
$("span#message-from").text("New Message From: " + data[0].SENDERNAME);
}
});
}
UPDATE:
Between the response I got below and a few emails to our developer who's in Romania, I was able to piece it together. I updated my code to what worked! The having just data.VIEWURL didn't work. I had to add the data[0].VIEWURL. So, thanks Matt for that one. Also, in my href i had to put in empty quotes or it would return NaN. No idea why.
Thanks!
Well, that JavaScript isn't going to work whatever you do on the C# side. You're attempting synchronous processing of the result of an asynchronous call.
Your C# doesn't look far off, for some reason I totally failed to read it correctly first time around. I've never used a .ashx in quite that manner, I've always just spat out my response from ProcessRequest, but if your code is getting called then I just learned something new. I do, however, notice that you're returning a serialized list, but only processing one element.
You could use a more LINQy approach to eliminate the explicit list filling, though:
var list =
from R in new Command("select top 1 o.name [SENDERNAME], view_url [VIEWURL] from MESSAGE m join OPR_SECD o on UPDATED_BY = O.RECNUM where VIEW_URL like 'conversation.aspx%' and DELIVER_TO in (select OPR_INITIAL from OPR_SECD where recnum = #CURRENT_USER_ID) order by m.RECNUM desc")
.AddInt("CURRENT_USER_ID", Common.UserID)
select new {
VIEWURL = R.GetString("VIEWURL"),
SENDERNAME = R.GetString("SENDERNAME") };
context.Response.Write(JsonConverter.SeralizeObject(list));
Your JS should look more like:
convDetails: function() {
$.ajax({
url: BASE_URL + "pages/services/messages.ashx?method=convdetails",
async: true,
data: {},
success: function(data) {
$("a.new-message-alert").attr("href", data[0].VIEWURL);
$("a.new-message-alert").text("New message from: " + data[0].SENDERNAME);
}
});
}

Accessing different elements in an array returned from a WebMethod

I have a WebMethod which returns a string of array:
[WebMethod]
public static string[] GetDataFromServer()
{
return new string[] { "one", "two", "three" };
}
I am calling the WebMethod using the following code:
$.ajax({
type: "POST",
url: "MyPage.aspx/GetDataFromServer",
data: "{}",
success: function (msg) {
alert(msg.d);
},
error: function (x, e) {
alert("The call to the server side failed. " + x.responseText);
}
});
Since the WebMethod is returning an array of string, when calling alert(msg.d);, I am getting all the elements of the array seperated by a ,. I understand that I can split the msg.d by the , seperator but I don't think that it is good practice. How can I access the different elements in the resulting array by index?
You should just be able to use msg.d[0], for example to get the first item in the array.

value not passing

I'm trying to send selected checkbox values to another asp page to update database.
$("#Delete_selected_Comment_button").click(function () {
var dataToBeDeleted = new Array();
$('.checkboxes_to_delete:checked').each(function (key, value) {
dataToBeDeleted .push($(this).val());
});
$.ajax({
url: 'http://myurl.aspx',
type: 'GET',
data: dataToBeDeleted,
success: function () { alert('yipee'); },
error: function () { alert("Ooff could not delete data"); }
});
});
Problem:
I am not able to retrieve any value in myurl.asp page.
I am doing:
String datagotfromajax= request.QueryString[dataToBeDeleted];
Am doing this incorrectly? Where is my mistake ? Can anyone help please?
An easy way would be to change one line:
data: "ids="+dataToBeDeleted.join(","),
And, in the server do:
string[] ids = Request.QueryString["ids"].ToString().Split(",");
With this you'll hava a string array in the server with the corresponding checkboxes values.
HOpe this helps.
dataToBeDeleted will be converted to a query string (if its not already) when sent to the server, that means it consists key-value pairs, i.e. foo=bar&fred=fish. On the server you can query individual key-value pairs using the syntax
string bar = request.QueryString["foo"];
You are passing an array as the data parameter. This won't work. You need to pass an object. If the object contains an array, this will be serialized appropriately. This means your code should probably look like this:
data: {
toBeDeleted: dataToBeDeleted
},
This will then be serialized appropriately (see $.param for the serialization process) and you can retrieve the values with your back-end code.

Categories

Resources