I am using the web kit browsers local database to temporarily store some data and when I want to access it I create an object
function patientSelectHandler(transaction, results) {
var row = results.rows.item(0);
var patient = new Object();
patient.name = row['name']
patient.dob = row['dob']
patient.gender = row['gender']
}
Is there a way to access this object from code behind, without having to populate textfields/labels/dropdowns and then get the values from there?
example as it is now:
function patientSelectHandler(transaction, results) {
var row = results.rows.item(0);
var patient = new Object();
patient.name = row['name']
patient.dob = row['dob']
patient.gender = row['gender']
$('#txtPatientName').val(patient.name);
$('#txtDOB').val(patient.dob);
$('#ddlGender').val(patient.gender);
}
edit:
Updating my example a bit:
var patientString = JSON.stringify(patient);
var inputField = $("<input type='text' name='hiddenField" + i + "' id='hiddenField" + i + "'></input>");
$('#Patients').append(inputField);
$('#hiddenField' + i).val(patientString);
and then a loop in the code behind
for (int i = 0; i <= count; i++)
{
string n = String.Format("{0}", Request.Form["hiddenField" + i]).ToString();
JObject o = JObject.Parse(n);
string name = (string)o["name"];
//now I can get all values into variables and use them when calling the web service
}
You don't need to set it to textfields for any reason...
I would probably do something like
var patientString = JSON.stringify(patient);
$('#myHiddenInput').val(patientString);
Otherwise, depending on the flow of your application, you can post that object in string form to the server using AJAX.
Then, you will have to use a method to parse that string back into object formation. I'm not to familiar with c# but i'm sure it would be easy to find or write such a method.
If you have many fields to send, you can JSON encode everything and put it into a single multiline text field (textarea). Then you can easily decode it on the server.
Keep in mind -
When your server code runs, it builds up a page object that it then uses to generate html to send to the browser. Once the html is generated that page object is destroyed. By the time the browser shows your page, your server resources don't exist any more.
When the browser submits a request for a page, it destroys the DOM for whatever page it's showing. So by the time your server starts, your javascript doesn't exist any more.
Thus, the two systems are normally completely separate. You can get around this by passing ajax json messages between client and server.
I would use AJAX post to store your JSON object on the server.
var str = JSON.stringify(...);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/validate",
data: str,
error: function(XMLHttpRequest, textStatus, errorThrown) {
...
},
success: ajaxCallback,
dataType: "json"
});
And on the server
[WebMethod]
public static string validate(Dictionary<string, object> patient)
{
...
//return your JSON response
}
And then just iterate through Dictionary object on the server (key - object parameter, value - it's value).
Related
I have a JQuery Ajax Call as per the following code:
$.ajax({
type: "POST",
url: "spaceplanning_database.asmx/GetRoomDataAttributes",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
restricted_attributes_global = msg.d;
console.log(msg.d);// "OBJECTID", "Room", "Floor", "OBJECTID_BLDG", "Room_GUID", "PKey", "SHAPE"
var featureLayer = new FeatureLayer("http://gisserver/xxx", {
mode: FeatureLayer.MODE_SNAPSHOT,
//outFields: [restricted_attributes_global], //doesn't work
outFields: ["OBJECTID", "Room", "Floor", "OBJECTID_BLDG", "Room_GUID", "PKey", "SHAPE"],
});
map.addLayer(featureLayer);
}
});
Basically, this calls a C# Web Service and gets some database column names (such as OBJECTID, Room). The column names are padded in the Web Service with double quotes, per
string allowed_loc = "\"" + reader["COLUMN_NAME"] + "\"";
in a loop.
The console.log in the code above shows the output for msg.d; but when this assigned to the restricted_attributes_global variable and used in the Esri query then I see an error:
esri.layers.FeatureLayer: unable to find '"OBJECTID","Room","Floor","OBJECTID_BLDG","Room_GUID","PKey","SHAPE"' field in the layer 'fields'
But, as in the code above, I copy/paste the console.log value as hard-coded then the Esri query works. Maybe I need to put the double quotes in C# in a different way, or type charset to something else in the Ajax call? What could be happening?
I think this question falls somewhere in between JQuery, C# and Esri queries.
As I figured out in my Comment above, I had to make an array object to pass to the outFields variable and I just couldn't make it work with the FeatureLayer mode. So I ended up using a QueryTask. Here is relevant code:
...//code as above this line
restricted_attributes_global = msg.d;
var array = restricted_attributes_global.split(',');//converting to array
var query = new esri.tasks.Query();
var queryTask = new esri.tasks.QueryTask("http://gisserver/xx");
query.where = "OBJECTID_BLDG=12";
query.outSpatialReference = { wkid: 102100 };
query.returnGeometry = true;
query.outFields = [array];// passing the array
QueryTask was the better route for my application anyway. The C# code is changed to remove the double quotes now:
allowed_attributes.Add(reader["COLUMN_NAME"].ToString());
Everything working like a charm now.
HTH.
I have a button on a website which sends an AJAX request to a .NET HTTPHandler. In the ProcessRequest method of this handler, it then took the query string parameters, and created a new WebRequest to another URL and appended the parameters onto it.
However, the AJAX request has been changed to use POST rather than GET (amongst other things).
This is what I need to do:
public void ProcessRequest(HttpContext context)
{
// Take POST data from request and create a new request
// with it to another URL
}
What makes it more complicated is that the POST data contains multiple arrays all called 'points' which hold latitude, longitude and altitude. So I can't use context.Request["points"] as that doesn't return an array of my points arrays. And I've tried using context.Request.Form.GetValues("points") but that doesn't seem to work, presumably because the data wasn't submitted as a form.
Edit:
AJAX request is:
$.ajax({
url: self.stationsAllFile,
data: data,
type: 'POST',
success: function (response) {
// store stations as kml string
self.stationsCurrent = response;
self.showStations(self.stationsCurrent, false);
self.listStations(self.stationsCurrent, finishedLoading);
var stations = $.parseXML(response),
$stations = $(stations),
$placemarks = $stations.find('Placemark');
$placemarks.each(function () {
var $placemark = $(this),
latLng = $placemark.find('coordinates').text(),
latLngSplit = latLng.split(','),
lng = latLngSplit[0],
lat = latLngSplit[1];
excludePoints.push(lng + ',' + lat + ',0.000000');
});
// do we need to go again?
if(endPoint < route.length) {
self.processRoute(route, endPoint + 1, excludePoints);
}
},
error: function () {
self.showError(self.language.errors.unknownError);
},
dataType: 'text'
});
Example POST data (pasted from Fiddler):
points%5B%5D=-2.2349300000000003%2C53.48073%2C0.000000&points%5B%5D=-2.26805%2C53.559020000000004%2C0.000000&type=route
I am trying to simply write out some data to my webpage as a result of a callback. Everything works up until the point where I need to output the result of the callback.
Client-side:
function toServer(data) {
var dataPackage = data + "~";
jQuery('form').each(function () {
document.getElementById('payload').value = JSON.stringify({ sendData: dataPackage });
$.ajax({
type: "POST",
async: true,
url: window.location.href.toString(),
data: jQuery(this).serialize(),
success: function (result) {
//this does not work because it just puts an entire source code copy of my site in there instead...
//document.getElementById('searchResults').value = result
console.log("callback compelete");
},
error: function(error) {
console.log("callback Error");
}
});
});
}
Server-Side: (on page load)
//holds actions from page
string payload = HttpContext.Current.Request.Form["payload"] ?? String.Empty;
// See if there were hidden requests (callbacks)
if (!String.IsNullOrEmpty(payload))
{
string temp_AggregationId = CurrentMode.Aggregation;
string[] temp_AggregationList = temp_AggregationId.Split(' ');
Perform_Aggregation_Search(temp_AggregationList, true, Tracer);
}
else
{
HttpContext.Current.Session["SearchResultsJSON"] = "";
}
The rest of the server-side code works properly and just handles the parsing of the incoming and performs a search of the db and then parses the search results into a JSON obj.
Currently, the only way the json obj gets written to the page is if I call it without the callback (just call it on page load). Also, in firebug, it looks like the entire page source is posting back as the 'result' of the callback. I do see my json result within the posted back 'result' but it also contains the entire page HTML.
Moreover, I can't seem to get the result to post to the page which is the whole point. Actually, I could get the result to post to the page by simply uncommenting that bit in the client side code but it posts a copy of my site and not the actual result I thought I created...
What am I missing? How do you explicitly state in the C# code what is returned to the JS callback as 'result'?
You get the entire page because you're making a request to an ASP.NET page. In fact, you're requesting the vary same page you're viewing. The server is returning what it would return if you were submitting a form.
To get JSON data, you need to create a web method to handle your request. Read this article, it will help you. It shows you how to return simple text, but you can return JSON too. Information on this MSDN article.
Finally, to make sure jQuery is parsing the server response as JSON, change your request and indicate it explicitly:
function toServer(data) {
var dataPackage = data + "~";
jQuery('form').each(function () {
document.getElementById('payload').value = JSON.stringify({ sendData: dataPackage });
$.ajax({
type: "POST",
async: true,
url: window.location.href.toString(),
data: jQuery(this).serialize(),
dataType: 'json',
success: function (result) {
//this does not work because it just puts an entire source code copy of my site in there instead...
//document.getElementById('searchResults').value = result
console.log("callback compelete");
},
error: function(error) {
console.log("callback Error");
}
});
});
}
I have a 2D javascript array that is filled with user data and checked for valid data.
How do I go about getting that 2D array passed to my c# code behind page?
I am going to use the c# code to push it to a database after further processing.
From searching it seems like I need to get it to some sort of json to pass it to the c# code, but i'm at a complete loss on how to do that exactly and then what to do once I get it to the c# code.
Javascript array looks like this
[["Q458","","100","85"],
["Q459","TS","90","65"],
["Q460","","80","15"]]
There is a simple way to achieve this with the Newtonsoft.Json library (available for download via NuGet Package Manager - in Visual Studio click Tools -> Library Package Manager -> Manage NuGet Packages for this solution and search for "Json").
First you send this array to your code-behind - probably via AJAX request supplying your array as a parameter. To create a JSON string out of your array object, use the JSON-js (https://github.com/douglascrockford/JSON-js) library's stringify function as follows:
var jsonArrayString = JSON.stringify( your_array );
This string you will now send to your server and use Newtonsoft.Json to deserialize to an two dimensional list or array:
JsonConvert.DeserializeObject<List<List<string>>>( yourJsonString );
or
JsonConvert.DeserializeObject<string[,]>(yourJsonString );
To expand on MZetko's answer, here's a method you can use with jQuery and Json.Net.
First, you'll need to set up a way to send the js array to your c# code. You can use something like this:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
var items = [["Q458", "", "100", "85"], ["Q459", "TS", "90", "65"], ["Q460", "", "80", "15"]];
sendToDb(items);
function sendToDb(inArr) {
var inString = JSON.stringify(inArr);
$.ajax({
url: "/Handlers/some-generic-handler.ashx",
dataType: 'json',
type: 'post',
data: { myVar: inString },
success: function (data) {
if (data.success == true) {
alert("Here's the first element in the array: " + data.firstElement)
alert(data.message);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
</script>
Now, you'll need to build a handler that will answer the ajax request. This page will use Json.Net. The code will look something like this:
public class some_generic_handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string myVar = "";
if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.Form["myVar"])) { myVar = System.Web.HttpContext.Current.Request.Form["myVar"].Trim(); }
var myArr = JsonConvert.DeserializeObject<List<List<string>>>(myVar);
string firstElement = myArr[0][0];
string response = String.Format(#"{{ ""success"" : true, ""message"" : ""Cool! We're done."", ""firstElement"" : ""{0}"" }}", firstElement);
context.Response.ContentType = "application/json";
context.Response.Write(response);
}
public bool IsReusable
{
get
{
return false;
}
}
}
Be sure to install Json.Net by PM> Install-Package Newtonsoft.Json, and then include the following reference:
using Newtonsoft.Json;
This demo will convert the js array to a string, send it to your handler page, the handler page will deserialize that string to a c# array, send back the first element in the array to the initial page, and then the initial page will alert the first element. In your application, you would use the handler page to insert data into your db table.
you can pass this from the client side to the server side using asp:HiddenField
Client
<asp:HiddenField runat="server" ID="myhf" Value="[['Q458','','100','85'],
['Q459','TS','90','65'],['Q460','','80','15']]"/>
Server
var ser = new System.Web.Script.Serialization.JavaScriptSerializer();
var strArray = ser.Deserialize<string[][]>(myhf.Value);
now strArray is a 2D array you can loop through it and do you database insertion.
I want to post data to a web service with ajax. there is my ajax code:
function Looping() {
var Grid = document.getElementById("<%= gvHastalar.ClientID %>");
var Row;
var Cell;
if (Grid.rows.length > 2) {
for (i = 1; i < Grid.rows.length - 1; i++) {
Row = Grid.rows[i];
Cell = Row.cells[3];
alert(Cell.innerHTML);
var html = $.ajax(
{
type: "POST",
url: "http://localhost:7753/HastaTahlilUyariServisi.asmx/f_HastaninAktarilacakAlislabTestleri",
data: "{_sTcKimlikNo:" + Cell.innerHTML + ",_iKlinikKodu:18001,_bAy:12,_iYil:2009}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: alert('success'),
error: alert('error')
}
).responseText;
Row.style.backgroundColor = "#D3EFD1";
}
}
}
And my webservice function's code is here:
[WebMethod]
[SoapHeader("_ticket", Direction = SoapHeaderDirection.In)]//SoapHeaderDirection.Out
public DataSet f_HastaninAlisLabTahlilleri(string _sTcKimlikNo, int _iKlinikKodu, byte _bAy, int _iYil)
{
try
{
string QSelect =
#"SELECT * FROM [V_EUCLID_SONUC]
WHERE MONTH(KAYITTARIHI) = " + _bAy + #"
AND YEAR(KAYITTARIHI) = " + _iYil +
AND TCKIMLIKNO = '" + _sTcKimlikNo + #"'";
return dbA.ExecuteDataSet(CommandType.Text, QSelect);
}
catch (Exception ex)
{
throw (ex);
}
}
There is a break point on function which is in the web service but debug never go that break point. I pasted webservice's url from browser but may be url is wrong. And when i run project, i have 3 alert.
First Cell's text its normal.Second alert is success and the last alert is error. I want to send parameters to f_HastaninAlisLabTahlilleri and user return dataset. How can i do this?
Thanks in advance
Here are a few remarks about your code:
success and error are callback functions, they should be defined like this:
success: function(data) { alert('success'); },
error: function(XMLHttpRequest, textStatus, errorThrown) { alert('error'); }
ASMX web services use SOAP by default unless you decorate them with ScriptServiceAttribute in which case JSON could be used to invoke a method. It is not clear from your code if the web service is decorated with this attribute.
When you pass parameters, you need to encode them, use JSON. stringify instead of concatenating strings:
data: JSON.stringify({_sTcKimlikNo: Cell.innerHTML,
_iKlinikKodu: 18001,
_bAy: 12,_iYil: 2009});
Use FireBug to inspect network AJAX requests and server responses and post them on StackOverflow to facilitate debugging.
You cannot put a break-point in the web-service code i.e. even the IDE would not let u debug the web-service code.... it is an old legacy the VS.Net IDE has since its inception... lets see if it is resolved in VS 2010.
The url that you have specified in the JQuery script is not equal to the name of the function in c# code. Isn't it the point. *f_HastaninAktarilacakAlislabTestleri* in url and *f_HastaninAlisLabTahlilleri* in c# code. Some reasons for such a problem can be wrong url or deference between argument list of client request and argument list of the server side method or action.