value not passing - c#

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.

Related

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.

Calling Url.Action in JQuery with multiple parameters

I'm trying to use Url.Action to call the controller c# function:
public ActionResult Setup(string ID, string Definition)
This function is located in the controller class MachineController.cs, and it returns a PartialView.
So, in with my script, i'm trying to call function 'Setup' with the line:
var selected = $('#dropselector').find(':selected').text();
$.get('#Url.Action("Setup", "Machine", new { ID = #Model.ID , Definition = "_holder"})'.replace("_holder", selected), function (data) {
$('#MachineSetup').replaceWith(data);
});
What seems to happen is the first parameter (ID) is passed no problem, but the second parameter (Definition) is always empty string. I've even tried assigning 'Definition' to #Model.ID same as the ID field as they are both strings, but it just seems to result in the same, ID is populated but Definition is an empty string.
The problem definitely relates to the passing of a second parameter, any ideas?
you could try the following
var selected = $('#dropselector').find(':selected').text();
$.get(
'#Url.Action("Setup","Machine", new { ID = #Model.ID })',
{
data:{definition:selected}
} ,
function (data)
{
$('#MachineSetup').replaceWith(data);
});
as the url will contain the Model.ID but the dynamic value of selected will change.
also if you are doing a Setup would you not consider a POST action to make sure the values are not cached on the client machine.

reading JSON data from aspx web form

I have an Regular ASP.Net web form (not a web service) that I'm trying to spit out JSON data which I'm then trying to consume. I have a 2 part question.
The 1st one is dealing with outputting the JSON data:
var reader2 = command.ExecuteReader();
while (reader2.Read())
{
var json = Json.Encode(new{
code = reader2[1].ToString(),
Revenue = reader2[4].ToString()
});
Response.Write(json);
}
reader2 contains 238 different entries. Right now the above Response.Write(json) returns 238 separate json strings:
{"code":"123","Revenue":"90.0000"}{"code":"234","Revenue":"90.0000"}
I think it might be helpful later (for question 2) if I had them grouped into 1 recordset.
{ "records": [ { "code":"123" , "Revenue":"90.0000" }, {
"code":"234" , "Revenue":"90.0000" } ] }
How would I do that with the above snippet using the reader and the System.Web.Helpers.Json?
The second question might be a direct result of how I'm currently outputting the JSON data from the first question. Ultimately I want to be able to read what ever I output from question 1 using this function. Right now my I set my dataType: "html" as that is the only thing I could get to return anything. However, that gives me a length for my msg of 32000+... Something isn't right.
What do I have to do to be able to read the JSON data output from my ASPX page?
function populateResults(code, district, year) {
$.ajax({
type: "GET",
url: "regular.aspx",
data: "code=" + code + "year=" + year,
dataType: "html",
success: function (msg) {
var results = msg;
$.each(results, function (index, result) {
console.log(result.code);
});
}
});
Re-reading the question after my comment, it's a little more clear now that "32000" isn't too much data in general, it's just that the data is being treated as one big string instead of as an array of objects.
This is probably because the data type is HTML, which is probably necessary because it's not seeing the response as correctly formatted JSON. I think you're right that it needs to be "grouped" though it might not need to be wrapped in a parent object like that. Try prepending with a [, appending with a ], and separating each with a comma. Maybe something like this:
var reader2 = command.ExecuteReader();
Response.Write("[");
var firstRecord = true;
while (reader2.Read())
{
if (!firstRecord)
Response.Write(",");
firstRecord = false;
var json = Json.Encode(new{
code = reader2[1].ToString(),
Revenue = reader2[4].ToString()
});
Response.Write(json);
}
Response.Write("]");
I had to throw in a little logic there to determine when to include a comma, since you don't want one before the first record or after the last record. There may be a more elegant way to do that, especially if you know the count coming from reader2. But hopefully you get the idea.
This should result in something more like this:
[{"code":"123","Revenue":"90.0000"},{"code":"234","Revenue":"90.0000"}]
Which by itself should be interpretable as JSON by the browser. This should allow you to set the data type:
dataType: "json"
Which should, in turn, give you what you're looking for in msg.
Edit: You may be able to simplify this a little more by turning the output from reader2 into an enumeration of objects and just using Json.Encode() on that whole thing. Maybe something like:
var records = new List<CustomRecord>();
while (reader2.Read())
{
records.Add(new CustomRecord {
code = reader2[1].ToString(),
Revenue = reader2[4].ToString()
});
}
Response.Write(Json.Encode(records));
And have a simple custom object:
class CustomRecord
{
public string code { get; set; }
public string Revenue { get; set; }
}

Array Passed to Controller Received as NULL

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

jquery submit model containing multiple objects

--I've deleted the original text to try to clean the post up a bit--
--------EDIT-------------------------------------------------------------------------
Here is some more info not sure if it helps anyone that's ran into this issue before.
Here is what my final object looks like in the JS script:
var DealerModel = {
Dealer: {
AccountId: 5678,
Name: "Austin",
City: "Who knows",
State: "TN"
},
Test: 111,
DealerCategories: [{Name: "Test1", Value:"Value1"},{Name:"Test2", Value:"Value2"}]
}
When I pass this into my controller via jquery it has the 111 value for Test, it shows that DealerCategories has 2 objects, but for both those objects as well as Dealer it shows NULL.
I've changed up the model/controller a few times and it seems no matter what if I pass in an object that has a sub json object it doesn't like that. I have a feeling this is something simple i'm missing.
the model binder knows how to bind arrays from JSON so you just have to give him something like this :
var DealerModel =
{
Dealer : 'my_dealer_value_here',
DealerContact = [] <- a list of Contrats here
}
and i think this should do it.
If your issue is with taking the leap from posting simple values like strings and numbers through jQuery.post, you can also provide json objects, like the one listed by Alex, above.
$.ajax({
type: "POST",
url: 'MYURL',
data: {
Dealer : {id:-1, accountId: '', name:'TheDealer'},
DealerContact: [{FirstName:'ContactName',...},{...},...]
}
});
And that bit of data should deserialize to your objects.

Categories

Resources