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.
Related
I have an UPDATE SQL transaction that connects to a SQL Server database using C# .NET 4.0 (I'm currently using SqlCommand.ExecuteNonQuery which is not Async so I'm sure I'm gonna need to change it). The transaction execution time is long (about a minute). I have ASP.NET application (Web Forms) and I wish to execute the transaction asynchronously while keeping the user able to interact with the application (navigating through pages). After the execution is finished, I wish to push kind of a notification to the user telling him that the transaction is finished.
I realize that my problem has two parts: the ADO.NET Async part and the part of triggering the application to push a notification to the client when the transaction is complete.
What's the best approach to implement both parts?
SignalR will fulfill your requirement
http://www.codeproject.com/Articles/315938/Real-time-Asynchronous-Web-Pages-using-jTable-Sign
or after SQl operation you can get response from Executenonquery and save it into hidden field, in client side you can use Jquery setInterval to check th hidden field value
Actually You can use jquery to do asynchronous call to the method that execute SQL transactions then you will return a message to the user after code execution has been finished.
For more information check the following example
Jquery Code
$.post( "PageName.aspx/UpdateMethodName", {}) //you can replace method name
.done(function( data ) {
alert(data);
});
Now in your ASPX page you must have a static method decorated with [WebMethod] attribute
[WebMethod]
public static string UpdateMethodName() //method name will be called from jquery
{
// your
return "Message";
}
More Information can be found here
JQuery.Post()
Using jQuery to directly call ASP.NET AJAX page methods
I hope that help
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.
I'm trying to call a code-behind function inside JavaScript and pass a parameters to the code-behind function.
For example:
<script>
var name;
<% createUser(name) %>
</script>
private void createUser(string Name)
{ // Do crazy stuff }
I'm doing this because some of the elements are dynamically created using jQuery, so I cannot access them in server side code. The example above is relatively simple and nothing close to what I'm trying to achieve, nevertheless, it does give you a good overview of my problem.
Thanks!
You can't directly "call" a code-behind function from JavaScript. JS runs in the client's browser, and C# is running on a server somewhere else. The two communicate using HTTP requests via the medium of a web server. You can fire off an HTTP Request from the client, and have a server page waiting to process such requests by delegating to code-behind functions:
Take a look at AJAX.
Call ASP.NET function from JavaScript?
I am developing an application in which I am displaying products in a grid. In the grid there is a column which have a disable/enable icon and on click of that icon I am firing a request through AJAX to my page manageProduct.aspx for enabling/disabling that particular product.
In my ajax request I am passing productID as parameter, so the final ajax query is as
http://example.com/manageProduct.aspx?id=234
Now, if someone (professional hacker or web developer) can get this URL (which is easy to get from my javascript files), then he can make a script which will run as a loop and will disable all my products.
So, I want to know that is there any mechanism, technique or method using which if someone tries to execute that page directly then, it will return an error (a proper message "You're not authorized or something") else if the page is executed from the desired page, like where I am displaying product list, then it will ecxecute properly.
Basically I wnat to secure my AJAX requests, so taht no one can directly execute them.
In PHP:
In php my colleague secure this PHP pages by checking the refrer of the page. as below:
$back_link = $_SERVER['HTTP_REFERER'];
if ($back_link =='')
{
echo 'You are not authorized to execute this page';
}
else
{
//coding
}
Please tell me how to the same or any other different but secure techique in ASP.NET (C#), I am using jQUERY in my app for making ajax requests.
Thanks
Forget about using the referer - it is trivial to forge. There is no way to reliably tell if a request is being made directly or as a response to something else.
If you want to stop unauthorised people from having an effect on the system by requesting a URL, then you need something smarter then that to determine their authorisation level (probably a password system implemented with HTTP Basic Auth or Cookies).
Whatever you do, don't rely on http headers like 'HTTP_REFERER', as they can be easily spoofed.
You need to check in your service that your user is logged in. Writing a good secure login system isn't easy either but that is what you need to do, or use the built in "forms authentication".
Also, do not use sequential product id's, use uniqueidentifiers, you can still have an integer product id for display but for all other uses like the one you describe you will want to use the product uniqueidentifier/guid.
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/