Call javascript with C# from WebService (.NET) - c#

I have a web page with JavaScript that calls C# methods using jQuery and AJAX. This works fine. I would like to know how to call JavaScript functions from the C# code, if this is even possible. If it's not possible, is there a sane alternative?

Assuming the browser initiates the interaction
In general, your server-side C# code will respond to interactions initiated by your client-side code. If you're looking for ways your C# code can initiate the interaction in the absense of a browser request, see the next section below.
If you're processing a full page response, then of course you can just output script tags containing the call you want to have occur. Make sure that the script is making the call after the function it's calling has already been defined by an earlier script tag, and if there's going to be DOM interaction be sure to put that script at the bottom of the page (or use jQuery's ready feature).
Responding to Ajax calls, it's possible for the C# code to return strings containing JavaScript code, which your in-page code would then execute (e.g., via eval or similar), but it's generally best to avoid that.
Instead, have the C# code return data in response to an Ajax call, and have your in-page code respond to that data by calling the appropriate function.
A bit of a hybrid of the two is to have your C# code return data that indicates what function to call and what arguments to supply to it, and to have a map of your functions that you index into with the function name, e.g.:
var functions = {
foo: function(arg0, arg1) {
alert("foo called with " + arg0 + "," + arg1);
},
bar: function(arg) {
alert("bar called with " + arg);
}
};
$.ajax({
url: "/path/to/resource",
dataType: "json",
success: function(data) {
if (data && data.fname && data.args) {
functions[data.fname].apply(undefined, data.args);
}
}
});
There, your C# code would return a string containing information encoded in JSON as an object with an fname property (a string giving a function name) and an args property (an array of arguments to pass to the function), which jQuery will deserialize into an object for you. Then we look up the function object in the map using its name (functions[data.fname]) and use the built-in Function#apply to call it and pass in the arguments. That works because you can refer to JavaScript object properties using either dotted syntax and a literal for the property name (obj.propName = 42), or using bracketed syntax and a string for the property name (obj["propName"] = 42), where in the latter example the string can be any expression, including a variable or property reference (name = "propName"; obj[name] = 42;) — which is how we're looking the functions up on the functions map.
I'm not suggesting you do that, just saying it's possible.
If you're trying to have the server initiate the interaction
If you want the server to reach out to the browser instead, you'll have to have some channel of communication established between them, either using the new (and variously supported) web sockets API, or various Comet techniques.

Javascript function can not called directly from C#, rather Javascript function/code block can register with page from C# code behind which is called after render or called when it is necessary.
//Register Script block for JS code
Page.ClientScript.RegisterClientScriptBlock(GetType(), "ScriptBlockKey",
"<script> alert('JS alert written in C# code behind.');</script>", false);
//Register Script block for calling JS function
Page.ClientScript.RegisterClientScriptBlock(GetType(), "ScriptBlockKey",
"SomeJSFunction();</script>", false);

Related

Create new Script within <div> from C# and Reload newly created Script

I would like to implement the following, which would appear to be fairly easy, but I have been searching for a working example without success.
i) I have an HTML Tag in an aspx Page with an identification:
<div id="demo" runat="server">
ii) This Tag contains the following Script Tag, which itself has an identification:
<script id="scriptdemo" type="text/javascript" src="http://www.myurl.com/myquery"></script>
iii) I have an AJAX call which calls a Server Function (which is working without any issue)
iv) From that Server Function, I would like to either modify the “src” Attribute of the Script, or create and insert a new script in the existing division with a new src if this solution is easier to implement.
v) After executing the Server Code contained within the Server Function, the flow is properly passed back to the client (here again, I do not have any issue with this process).
vi) Once back on the client, I would like to refresh/reload the newly created script (or updated src attribute) using JavaScript/AJAX (either standard Javascript or JQuery).
Would someone have a working example of such code?
Check out http://api.jquery.com/jQuery.getScript/
It's basically shorthand for $.ajax with datatype as "script". This will load a script file for you, and give you the chance to run a callback when it's done.
$.ajax({
url: "your/ServerMethodThatReturnsScript",
dataType: "script",
success: successCallback
});
becomes
$.getScript("your/ServeRMethodThatreturnsScript", function() { /* some success callback */ });
In the event you can't do this but CAN make an ajax call to your server, you can use the eval method to execute any string that is in the form of javascript:
eval("/*some javascript*/");

How can I inject javascript from C#?

I'm trying to invoke javascript from C# in my project, I want to call a javascript function that I've defined with parameters but I'm stuck on how to do it.
MainPage.xaml has this my:CordovaView that wraps my phonegap project, but I'm a little lost on how to "inject" and run javascript into it.
Has anyone done this? I'm trying to do push messages
I haven't done this with cordova per se, but in general you just need to remember where the code is executing. The C# code is executing on the server, and the javascript is executing on the client, so, you want your C# to emit a value that can be consumed by the client.
The following javascript snippet is based on Razor engine syntax, hopefully it's enough to get you started.
function alertVar(someVal) {
alert("JS, someVal = " + someVal);
}
$(document).ready(function() {
// in this case the server interpolates #Model and returns HTML with the value replaced
// wrap it in quotes so the js engine treats that value as a string
// this method will then fire when the document loads
alertVar("#Model.ServerValueForClient");
});
This is the html that that the server would send to the client after interpolation (assuming that somewhere on the server you set the value #Model.ServerValueForClient = "set by the server";)
$(document).ready(function() {
// in this case the server interpolates #Model and returns HTML with the value replaced
// wrap it in quotes so the js engine treats that value as a string
// this method will then fire when the document loads
alertVar("set by the server");
});
HTH

Call C# function from Javascript in aspx webform and then reload page

Trying to figure out how to call a c# function in a webform. I tried both ajax and windows.location but could just be off on my path. Trying to send it my c# code at SpeakerList.aspx/update and then gonna attach two variables i have in javascript which shouldnt be too bad. But want it to hit the C# function then reload the page so hoping there is just an easy call im missing.
buttons: {
"Save": function () {
var combo = ASPxClientControl.GetControlCollection().GetByName('DropDownList1');
var value = combo.GetSelectedItem().value;
var billID = $("#billID").val();
window.location = "SpeakerList.aspx/updateRec";
}
You might want to try using WebMethods:
http://aspalliance.com/1922_PageMethods_In_ASPNET_AJAX.all
This allows you to call a function in your page's code behind using JavaScript.
Assuming you are using MVC, you probably want to return a JSON result. An easy way to consume Json within your client webpage is using JQuery. You can return JSON as as the output of a webpage, but I don't recommend it. Create a separate service point that repesents the JSON method.
It is hard to tell what you are actually trying to accomplish, but the normal usage pattern for a JSON method is the supply the parameters as part of the querystring (which you can refactor with routing if you want). The result is then just a JSON packet.
Personally, I like JSON.Net for server side JSON, but you don't actually need this. Look up JSONMethod for examples, etc. that will show you how to do this.
From the browser client, JQuery has a json method, but I personally recommend using the more generic ajax method a JQuery so you can use the handlers for success, error and completion. E.g.
$.ajax({
url: "http:...",
data: queryparm,
cache:false,
timeout:15000,
success: function(data){
jresult = $.parseJSON(data);
...
},
error:function (xhr, ajaxOptions, thrownError)
{
setErrorMsg("Error getting search results: " + thrownError);
}
});
EDIT -- Actually, I've done this exact same thing with webforms too, code is essentially identically (if you use JSON.Net on the server side). You don't have the routing options to make the urls REST compliant, but as an internal json web service, you probably won't really care about that.
As a webpage (.aspx) page, you can use a "postback" this is the simplest method for a web form. You can always declare some hidden fields to use for data passing if you are not passing back a native "control" value. If you don't know how to do this, you need to read a tutorial on using web forms.

The equivalent of C# consuming a WCF method in JavaScript (jQuery)

I have a running WCF service that exposes a method GetStuff(String type). It's called by the automatically created client class, so the syntax is embarrassingly simple.
ServiceClient client = new ServiceClient();
String response = client.GetStuff("other's");
client.Close();
The straight-forward question is this. How do I convert that to a call in JavaScript (possiblyusing jQuery) in an easy way?
After some serious googling, I concluded that I'm only going to find examples of how to consume a JSON-formatted stream using jQuery. I prefer not to touch the service-side of the software, if at all possible.
I tried the code below (along with a bunch of derivatives that I could think of) but the error I got was "No Transport" and googling that didn't yield anything that I got me going.
$.ajax({
type: "GET",
url: "http://hazaa.azurewebsites.net/Service.svc",
success: function (response) { console.info(response); },
error: function (response) { console.error("Error! " + response.statusText); }
});
Will I have to write a totally different service that exposes the data in JSON format? How do I specify that the service is supposed to call this or that method? Am I out of luck and these convenience methods are for .NET clients only?
Please note that I've got another way of getting the data where I want, not using JavaScript at all but I'd prefer to see if this is (easily) doable too.
I would convert server method to use web invocation = WebInvoke attribute. Here you can specify uri for the method call.
Link to the info
Look into Jquery SOAP .. http://plugins.jquery.com/soap/ etc.
haven't tried it myself but it's the kind of thing you might be needing here.

Call a Javascript Method from code-behind Web Method

I have a web method in my code behind:
[System.Web.Services.WebMethod]
public static string GetStateData(string state)
{
//this is where i want to call a javascript method "GetItems"
}
I have a javascript method that retrieves some values for me and I want to get use one of those values in my web method
function GetItems() {
var variable1= $("#<%=Item1.ClientID %> input:checked");
var variable2= $("#<%=Item2.ClientID %>").val();
return [variable1.text(), variable2.val(), variable2];}
I've searched for ways to call the javascript method from the web method but every time my search results in how to call a web method from javascript.
I did find this but it was done from the code-behind of a silverlight project and when I tried adding the correct reference to my code-behind it wasn't there
var result = HtmlPage.Window.Invoke("GetItems");
Is there a reference I'm missing?
Thanks for your response
You can't do that. Your calling a webmethod through AJAX. your sending small pieces of information to a static method on the server that knows nothing about the specific page object (That isn't static).
What you want to do is send those values and data in the AJAX call to the webmethod. Your not making a full postback so you know nothing about the current state of the page except what you pass as paramaters to the webmethod.
Either send the information in the first place or return with some kind of flag when you want the information and get the client to make an ajax call back to another function with the information and let it continue from there.
Instead of trying to call javascript from a webmethod use the return value of the webmethod to decide what javascript function to call.
Calling javascript from a webmethod is not possible as far as I know - you need to understand the distinction between server side and client side code.

Categories