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?
Related
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.
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.
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.
Everyone I am using C#.NET for the task. Let me explain briefly what i need actually. I have a WEB application in ASP.NET C# and the value/data inserted by the user in the 'TextBox'(Employee_name:) needs to be passed to desktop application on the same corresponding 'TextBox' say "Employee_name:" So how do i make it. Thanks.
Web applications can not initiate a communication. So you can't do this the way you'd (probably like).
You can have your desktop application call a method in you ASP.NET application and get back the value and then put it in that required textbox.
However, that would mean a two step process Since you'd have to know when to ask the GUI application to go get the data from the ASP.NET application and depending on your situation, you'll probably have to pass additional information to the ASP.NET application so it can provide the value from the correct "record" as well.
EDIT
Simple way to achieve this, using just regular Http request (no web services or WCF)
The Mark up in an .aspx file should have no html. Just the page directive like so:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="HttpTaskServer.WebForm1" %>
In your code behind file (.cs file of the page) you could do something like this:
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.HttpMethod == "GET")
{
//Some parameter passed in by the client via QueryString (url)
var id = Request.QueryString["id"];
string data = GetTheData(id);
Response.Write(data);
}
}
}
For an example of how to make an http call from a GUI/Console application. Take a look at Code Listing 9 (the last code listing in the blog post). the link below will take you straight to code listing 9
http://www.matlus.com/httpwebrequest-asynchronous-programming/#codelisting9
I suggest:
- A webservice (WCF?) running on the IIS
- A webservice consumer in the desktop
The desktop client polls the web server if he has something for him on a regular interval. That or use WCF to set up duplex communication. That way the server can inform his clients the textbox has been changed. The communication still needs to be initiated by the desktop client.
I assume the scenario you are referring to here is a Front end web application and backoffice windows application. I am not sure why would need the data to be passed in real time but my suggestion would be to get your operation from Web application completed/stored in Database and then have that data pulled from DB to your windows application.
How to do it? I am completely new to this and wish to start learning it. I am going to have a tree structure, most probably a html/Javascript tree which will need to be saved into the database through Web Services.
What is the most efficient way to do this with ASP .net web services + asp.net 3.5?
UPDATED:
thanks for all the answers, I am still missing some pieces to this scenario, namely:
1) when the node is to be added to the tree, a user will get a pop-up, where some info will be entered, saved in the database, and a integer code returned from the database. Upon it's return, I need do some logic, and insert a node(or several) into the node selected. And so on, so forth. SO from what i understand, this logic (the meat of the code) will have to be performed on the client, in my Javascript code.
2) What would trigger the tree "refresh" after the pop-up is closed?
3) Where is .net with this picture at all? From what I gather, no server-side coding is performed here at all (aside from Web Services).
Is that the general direction these days, step away from server-side coding with .net controls and use a Javascript lib of choice + web services?
Thanks everyone.
You can achieve this by using ASP.net Ajax calls. On the server-side you create a webservice (WCF or asmx) having the attribute ScriptService:
namespace MyCompany.Project.Services
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class MyWebServiceClass : System.Web.Services.WebService
{
[WebMethod]
public string GreetFromServer(string name)
{
return "Hello, " + name;
}
}
}
On the page, you add a ScriptManager referencing your webservice.
<asp:ScriptManager id="scriptManager" runat="server">
<Services>
<asp:ServiceReference Path="~/Services/MyWebServiceClass"/>
</Services>
</asp:ScriptManager>
Then on the client side (JavaScript):
function invokeService(){
MyCompany.Project.Services.MyWebServiceClass.GreetFromServer("Juri", onSuccess, onFailure);
}
function onSuccess(result){
//check if result different null etc..It will be in JSON format, so deserialize
//use result
}
function onFailure(){
//handle errors
}
That should just be a hint on how to create a service and access it from within JavaScript. I mostly wrote it out of my head now, without checking it.
A hint: use Firebug! It's really great for verifying the data that is sent back and forth between your JavaScript client code and the webservice on the server-side.
I've just written a blog post with a downloadable example that describes the communication of client-server using asmx as well as WCF webservices.
Encosia.com has everything you need:
Using jQuery to Consume ASP.NET JSON Web Services
I would suggest you use jquery on the client side in your html / Javascript tree. Here is a tutorial to get you started on using jquery with asp.net
http://dotnetslackers.com/articles/ajax/Using-jQuery-with-ASP-NET.aspx
Have a look
Consuming a Web Service using ASP.NET Ajax