How to send data from C# to JavaScript/AJAX webpage - c#

Basically, I have a need for a c# server to be able to send data back to an HTML5 webpage which has previously send data to the server. The server is retrieving data from another application and this data then needs to be send to the webpage to be displayed.
This c# server is running on .NET CF 3.5 so websockets are not an option (not supported).
I have seen some suggestions elsewhere but nothing which fits the necessary criteria for this particular situation. Most other implementations seem to work on the basis that the webpage will only be waiting for this data to be sent over.
Any and all suggestions welcome!

If websockets are not an option then you are left with Comet.
Client-side you could do something like this :
(function poll(){
$.ajax({
url: "url",
success: function(data) { /*display data*/ },
complete: poll,
timeout: 30000 });
})();
Which means an ajax request will be sent every 30 seconds.
This is not as performant as websockets but it works quite well.

Create an .aspx page and remove all the HTML from it. Call it GetData.aspx
In the code behind of GetData.aspx.cs you can receive the POST data from the HTML5 page.
Do work.
Use jquery.
$.post("GetData.aspx",{name: value},function(json){
// put processing instructions here.
});

There are two ways to do this :
Using a ASP.NET web-page
Create HTML element that calls a javascript function
Inside of the javascript function, use ajax to make a POST to a ASP.NET Web Page (that uses C# as back-end)
Get the returned value in the ajax "success" block.
Use as you wish...
Using a jSON string return
Create HTML element that calls a javascript function
Inside of the javascript function, use ajax to make a POST to a Web Service (that uses C# as back-end), that returns a jSON string.
Use the returned jSON data in which ever way needed.
I personally prefer jSON, as it emulates a data set, and works well with HTML and ajax.

Related

Using config vars with angular and JQuery

I have an .NET application that uses mostly AngularJS, but for getting some things to work on IE9 we used sometimes a Jquery plugin to fix it (e.g. file upload)
Then on the other side there is an API that handles that application. But the API and the App won't be running on the same urls, so as good practice I would love to have 1 place where all the URl's can be set for where the API is where you can find the videos, ....
but how can I handle all this?
If i set them on the angular side, the controller is loaded after the JQuery,
so the value is undefined.
It can't read the web.config because it's just plain html files that are getting loaded. so no support from C#.
And didn't find any way on loading it in via JQuery.
Any suggestion on how to do this?
You can set it as a basic Object so scripts outside of Angular can use it. When you need to use it in the app, you can either require it directly or set it as a constant or create a service using it.
For example,
var api = {
baseUrl: 'www.moo.com/api/v1',
dogs: '/dogs',
cows: '/cows'
};
alert('This alert was created prior to angular module declartion with your api: ' + api.baseUrl);
angular.module('myCheeseIsGoodApp', [])
.constant('apiConstant', api)
.controller('TestController', ['$scope', 'apiConstant', function($scope, apiConstant){
$scope.apiConstant = apiConstant;
}]);
Here is a plunkr to check out how it works.http://plnkr.co/edit/fnqcwHxgxgrZlCpryMiC?p=preview
Keep in mind this was just a quick way to show you how to use it, but you may want to make it a bit more elegant.

Is there a way to send array on javascript to controller other than get or post method??

I am using ASPX and C#.
Is there a way to send an array on javascript to controller other than get or post method, or ajax or jquery?
I tried use the Url.Action code but seem like unable to parse the value in javascript to it.
This is how I pass the value:
<% Url.Action("Action","Controller",new { item = %> users <%});%>
But it gave me an error on the Brace '}'. State that invalid expression term.
The Javascript runs in the browser. The only way to communicate with the controller running on the server is through a http request such as GET or POST (or other HTTP verbs, or websockets or SignalR, but that's probably not applicable here).
Url.Action is a C# method that is called and evaluated entirely on the server, before producing the html sent to the browser. You can't reference a javascript variable in that call, so what you've tried is not only a syntax error. It is simply not possible to do that at all.

how to call javascript function at backend in asp.net?

If I want to call a javascript function after some code has been run in backend, how to do that? I don't want to add onclientclick event in frontend. I need to run the frontend function after a certain backend code has been run. Thanks in advance.
The best bet is to use Page.RegisterStartupScriptBlock.
When you submit to the server, the server is going to process your request and any other event / code that is required. It will then send back to the client the response.
If you want a user to invoke an action / event (say a button click), have it hit the server and then do some Java Script action after that please look at the following posts:
http://forums.asp.net/t/1003608.aspx/1
http://wiki.asp.net/page.aspx/1574/differences-between-registerclientscriptblock-amp-registerstartupscript-and-how-they-work-with-ajax-update-panel/
http://www.codeproject.com/KB/aspnet/ClientServer.aspx
The way (I) would do this is to refactor my code so that the code behind is called from a jQuery post to an ashx code file.
then on return of that function i can run whatever I like.
If you want details, let me know.
However, if this is not useable, then you could either place a property in your aspx page;
public string Action { get; set; }
then in your html;
var action = '<%= this. Action %>';
and perform an action.
Or you might set a hidden field to a value and check against that.
edit
this largely depends on when in the life cycle the code behind is being run. On ajax postback, on initial execution? When?
Client Script in ASP.NET Web Pages is the MSDN reference that you probably want.
The best way i can think of to do this is with web sockets. There are a few c# web socket implimentations around, such as Nugget. This allows you to open a socket with your client and allows for the possibility of the server proactively contacting and sending data to the client. There are other techniques to have the server talk to the client such as long polling. This way you can have the server call the client once something has happened on the server.

Real-time updates like Twitter

How do you implement a real-time update like Twitter does ("423 more tweets since you started searching")? I need to refresh my page at least every 10 seconds. I'm using ASP.NET MVC and jquery.
You could use the setInterval javascript function which allows you to poll the server for updates at regular intervals using AJAX:
window.setInterval(function() {
// This will be executed each 5s
// TODO: query your server for updates probably using AJAX
// example with jquery:
$.getJSON('/arethereanyupdates', function(data) {
if (data.isupdates) {
alert('yeap there are updates');
}
});
}, 5000);
There's also a push technology in HTML5 called WebSockets which allows the server to notify the client for updates but of course you will need an HTML5 compatible browser which nowadays is not difficult to find and a WebSocket API compliant server.
You can do an AJAX call to your server asking for updates, if the answer is positive (there are new things) you can show a javascript windows advising the user or just update the page content you need.
regards.
UPDATE: This how-to implements similar behavior
In the absence of long-polling (aka COMET) support in todays browsers (this should, however, change soon, with HTML5), I'm polling the server every n seconds using AJAX request and sending the timestep of the latest visible entry/item/tweet/whatever. Then the backend count the number of newer items and returns it back to the browser.

Is it possible to fill in an Ajax form programatically?

I'm doing some automation work and can make my way around a site & post to HTML forms okay, but now I'm up against a new challenge, Ajax forms.
Since there's no source to read, I'm left wondering if it's possible to fill in an Ajax form progamatically, in C#. I'm currently using a non-visible axWebBrowser.
Thanks in advance for your help!
Yes, but I recommend using a different approach to requesting/responding to the server pages including the regular pages, and the AJAX handler pages.
In c#, try using the WebRequest/WebResponse or the more specialized HttpWebRequest/HttpWebResponse classes.
Ajax is no more than a "fancy" name for a technology that allows Javascript to make HTTP requests to a server which usually implements some handlers that produce specialized, light-weight content for the Javascript caller (comonly encoded as JSON).
Therefore in order to simulate AJAX calls, all you have to do is inspect your target application (the web page that you want to "post" to) and see what format is used for the AJAX communications - then replicate the page's Javascript behavior from C# using the WebREquest/WebResponse classes.
See Firebug - a great tool that allows you to inspect a web page to determine what calls it makes, to which pages and what those pages respond. It does a pretty good job at inspecting AJAX calls too.
Here's a very simple example of how to do a web request:
HttpWebRequest wReq = (HttpWebRequest)WebRequest.Create("http://www.mysite.com");
using (HttpWebResponse resp = (HttpWebResponse)wReq.GetResponse())
{
// NOTE: A better approach would be to use the encoding returned by the server in
// the Response headers (I'm using UTF 8 for brevity)
using (StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8))
{
string content = sr.ReadToEnd();
// Do something with the content
}
}
A POST is also a request, but with a different method. See this page for an example of how to do a very simple post.
EDIT - Details on Inspecting the page behavior with Firebug
What I mean by inspecting the page you're trying to replicate is to use a tool (I use Firebug - on Firefox) to determine the flow of information between the page and the server.
With Firebug, you can do this by using the "Net" and "Console" panels. The Net panel lists all requests executed by the browser while loading the page. While the "Console" will list communications between the page and the server that take place after the page has loaded. Those communications that take place after the page has loaded are essentially the AJAX calls that you'll want to replicate (Note: Network monitoring has to be enbled in Firebug for this to work)
Check out Michael Sync's tutorial to learn more about Firebug and experiment with the Console panel to learn more about the AJAX requests.
Regarding "replicate the page's behavior from C# using the WebRequest/WebResponse" - what you have to realize is that like I said earlier, the Javascript AJAX call is nothing more than an HTTP Request. It's an HTTP Request that the Javacript makes "behind the scenes", or out-of-band, to the web server. To replicate this, it is really no different than replicating a normal GET or a normal POST like I showed above. And this is where Firebug comes in to play. Using it you can view the requests, as the Javascript makes them - look at the Console panel, and see what the Request message looks like.
Then you can use the same technique as above, using the HttpWebRequest/HttpWebResponse to make the same type of request as the Javascript does, only do it from C# instead.
Gregg, I hope this clarifies my answer a little bit but beyond this I suggest playing with Firebug and maybe learning more about how the HTTP protocol works and how AJAX works as a technology.
Have you looked at using Selenium. AFAIK, you can write the test cases in C# and I know our testers have successfully used it before to UI Test a Ajax enabled ASP.NET site
http://seleniumhq.org/

Categories