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
Related
Basically what I want to do is this this but I can't seem to find something similar for webview XAML control. What I ultimately need to do, is capture an incoming json file from the webview. As is, I get a bad request from the server and unsupported file exception from the webview. I thought about injecting a javascript so that it would alert me, I could get the body of the incoming json and bypass all the errors.
There are two main things you can do:
Call functions programically
Inject any code by using the HTML string
Function Calling
You can use InvokeScript to call javascript functions.
If you have in a webpage with a script:
<script lang="en-us" type="text/javascript">
function myFunction() {
alert("I am an alert box!");
}
</script>
Then you can in C# call:
MyWebview.InvokeScript("myFunction", null);
Which will execute the script function myFunction.
Injecting Text
If you download the HTML page and all other needed files(using the Windows HttpClient), you can inject any code by manipulating and then Navigating to string.
Lets say you want to change the above script to add another function, "HelloWorld", then you can
Search the file for something you know will be there, such as: <script lang=\"en-us\" type=\"text/javascript\">
Using string manipulation, add the desired text, such as a function (but this can be anything)
Navigate to the String
The C# code:
string MyWebPageString = GetWebpageString(WebpageUri);
string ScriptTagString = "<script lang=\"en-us\" type=\"text/javascript\">";
int IndexOfScriptTag = MyWebPageString.IndexOf(ScriptTagString);
int LengthOfScriptTag = ScriptTagString.Length;
string InsertionScriptString = "function SayHelloWorld() { window.external.notify(\"Hello World!\");} ";
MyWebPageString = MyWebPageString.Insert(IndexOfScriptTag + LengthOfScriptTag + 1, InsertionScriptString);
MyWebview.NavigateToString(MyWebPageString);
The result will be that the navigated to Webpage will look like this:
<script lang="en-us" type="text/javascript"> function SayHelloWorld() { window.external.notify("Hello World!");}
function myFunction() {
alert("I am an alert box!");
}
</script>
Since the injection can be applied to any area, even the HTML, you should be able to figure something out.
Hope this helps. Good luck.
This answer was based on this MSDN blog
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.
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);
Suppose I have a C# variable named currentTab in my razor view.
I have javascript codes that says..
<script type="text/javascipt">
function CurrentTabReturner(){
var currTab = $("a.current").attr("id");
return currTab;
}
</script>
Now I want to do this:
#currentTab = CurrentTabReturner();
Is it possible? Or are there any other ways to achieve this?
Thanks in advance.
Is it possible?
No it is not possible. Server side variables exist on the server. Client side javascript runs inside the client browser much later, where no more any server variables exist. So trying to assign a server side variable to a client side function simply doesn't make sense. On the client you could send normal or asynchronous (AJAX) requests to the server so that server side variables can be updated.
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.