Why can't i run a javascript function from c# code? - c#

This is a part of the C# code where i want to insert the network graph:
DetailsBody3.Text = "<tr class=\"space\">";
DetailsBody3.Text += "<td>" + "<div id=\"center-container\"><div id=\"infovis\"></div> />";
DetailsBody3.Text += "</div></td>";
DetailsBody3.Text += "</tr>";
In the "infovis" div in the graph code, the graph exists.
And in the graph javascript file:
function init1(){
// init data
}
var fd = new $jit.ForceDirected({
//id of the visualization container
injectInto: 'infovis',
// some other code,
}
I want to call the int1() function and draw the graph in the table created in C# above.

Javascript code runs in the browser. Your ASP.Net C# code runs in the server.
What you actually want to do is add this to the section of your your .aspx file:
<script type="text/javascript">
$(document).ready(
function(){
init();
}
);
</script>
This will call your javascript init() method once the page has loaded.

Try...
Page thisPage = HttpContext.Current.Handler as Page;
if (!thisPage.ClientScript.IsStartupScriptRegistered("run_init1")) {
thisPage.ClientScript.RegisterStartupScript(
thisPage.GetType(),
"run_init1",
"init1();",
true);
}
The above may need to be adjusted a bit depending on what version of the .Net Framework you are using (this works with version 4.0).

Related

Unable to call jQuery function from class file in C# project

I am working on C# project. On masterpage,I have a jquery function named "myfunction" .
While trying to call this function from a class file I am getting error on browser console "Uncaught ReferenceError: myfunctionis not defined".
function myfunction(){
// code
}
string script = "";
script = "<SCRIPT language='javascript'>myfunction(); </SCRIPT>";
var obj = ((Object)(HttpContext.Current.Handler));
Type scriptType = obj.GetType();
ClientScriptManager cs = ((Page)(HttpContext.Current.Handler)).ClientScript;
cs.RegisterStartupScript(scriptType, "alert", script.ToString());
While working on any C# website, I can call this function from class file as well but here getting error. Even if I use update panel then function executes but without update panel its not executing.
Change the type on the script declaration:
script = "<SCRIPT language='text/javascript'>myfunction(); </SCRIPT>";
Remove the redundant ToString() call:
cs.RegisterStartupScript(scriptType, "alert", script);
And make sure myfunction() is output on the HTML before your script is inserted.

Script src tag breaks

I have made previous posts about my custom visualization not working in Spotfire:
https://stackoverflow.com/questions/25390099/awesomium-javascript-handler-being-called-indefinitely
Returning value to C# function from Javascript not working in Awesomium
and I have finally narrowed it down to the offending line.
In my document, I load a source script:
<script src="http://d3js.org/d3.v3.min.js"></script>
This seems to break my entire custom visualization; it infinitely tries to reload the page, from what I've seen. Here is my C# code:
private void WebViewOnDomReady(object sender, EventArgs eventArgs)
{
webView.DomReady -= WebViewOnDomReady;
webView.CreateObject("jsobject");
//webView.SetObjectCallback("jsobject", "callNETNoReturn", JSHandler);
webView.SetObjectCallback("jsobject", "callNETWithReturn", JSHandler);
//webView.ExecuteJavascript("myMethod()");
var result = webView.ExecuteJavascriptWithResult("myMethodProvidingReturn('foo')");
MessageBox.Show("Stuff:" + result.ToString());
}
private void JSHandler(object sender, JSCallbackEventArgs args)
{
var result = webView.ExecuteJavascriptWithResult("myMethodProvidingReturn('foo')");
MessageBox.Show(result.ToString());
MessageBox.Show("Got method call with no return request");
}
And here is my Javascript code:
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
function myMethod() {
document.write("In myMethod, calling .NET but expecting no return value.<br/>");
jsobject.callNETNoReturn();
}
function myMethodExpectingReturn() {
document.write("In myMethodExpectingReturn, calling .NET and expecting return value.<br/>");
var returnVal2 = jsobject.callNETWithReturn("foo");
document.write("Got value from .NET: " + returnVal2 + "<br/>");
}
function myMethodProvidingReturn(whatToReturn) {
var returnVal = whatToReturn + "bar";
document.write("Returning '" + returnVal + "' to .NET.");
return returnVal;
}
</script>
Interestingly enough, the HTML loads fine if I don't try and call a Javascript function and get the return value in C#. However, when I try to return the result of the JS function and print it in C#, including the script src line breaks my entire code; it infinitely returns a blank message judging from the MessageBoxes that I have set.
This is completely baffling me, as it seems to mean that the HTML is being loaded over and over again. Setting the script src tag, for some odd reason, causes this infinite loop.
What exactly is happening?
Thanks

Call C# code behind function from jstorage

I am using the below code to store data using jstorage. i can;t understand what is load_data_from_server(). Please help me to call a code behind function from jstorage
<script src="prototype.js"></script>
<script src="jstorage.js"></script>
<script>
// Check if "key" exists in the storage
var value = $.jStorage.get("key");
if(!value){
// if not - load the data from the server
value = "hai";
value = load_data_from_server() //I want to call c# code behind function here
// and save it
$.jStorage.set("key",value);
}
</script>

How to dynamically generate and send jQuery to the webpage from C# AND have it work

So, I am dynamically generating jQuery using C# and sending it to the webpage.
The problem is it appears to be generating correct jQuery according to the file and according to Js Fiddle but it does not actually work on the page.
The jsFiddle is here http://jsfiddle.net/ER2hE/
Now I looked up how to send javacript to the website. It should work like this.
http://msdn.microsoft.com/en-us/library/bb359558.aspx
and my code which does that is this method
private void sendScript(string script)
{
const string someScript = "alertMe";
//send the built script to the website.
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), someScript, script, true);
}
This is super simple it has worked for other pieces of code calling. But it has not for this instance.
The code that calls it is this in my C#
private void populateGroups()
{
//this generates correct javascript according to the file and JS fiddle but unfortunately doees not work.
string splitme = "USE ACES SELECT GroupName, GroupID FROM PrimaryGroup ORDER BY GroupName";
DataTable dt = fillDataTable(splitme);
string script = "";
foreach (DataRow dr in dt.Rows)
{
//add the locations to the <select> box
script += " $('#groupList').append('<option value=\" " + dr.ItemArray[1].ToString() + " \"> " + dr.ItemArray[0].ToString() + " </option>'); ";
}
sendScript(script);
JSErrorLog(script, "GROUPS");
}
The whole thing is being called on startup
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack == false)
{
populateMakes();
populateLocation();
populateGroups();
}
}
The jQuery its generating also works in JSFiddle I am pulling this from a method that writes the javascript it generates in a method calling here is the fiddle JSErrorLog.
http://jsfiddle.net/ER2hE/
Oh and my html in my aspx file looks like this
<div class="row2">
<span>Group</span>
<select id="groupList" multiple="multiple" onclick="setGroups()" class="normalsize">
</select>
</div>
I believe that is everything. I just want my stuff to work. I am willing to post any additional code, just ask. If you have an idea as to why its not working, let me know.
When does it actually execute that code? Before or after the element with id "groupList" exists in the DOM? My guess is before.
Solution? Wrap your code inside a document.ready handler.
jQuery(function($) {
$('#groupList').append('<option value=" 46 "> AC Units </option>');
// etc etc
});
Return simple string js code. And run it with eval()

how to pass session value from code behind to javascript

i have made a session variable Session["Background1"] = value; in one of my code behind function i want to retrieve this value in my javascript function.
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "SessionValue", "var sessionValue = '" + Session["Background1"] + "';", true);
Personally, I prefer to do it the scripting way. Suppose your variable is currently declared in your Javascript as:
var background1 = null; // TODO: Add value from session.
To add the value from session, all you need to do is this:
var background1 = '<%= Session["Background1"] %>';
When the page is output by ASP.NET, the expression between <%= and %> is evaluated and written to the page, effectively becoming a Response.Write. As long as the member is available in your page at the public or protected level, you can push it into your Javascript it in this way.
I find this approach easier to work with than the obnoxiously verbose ClientScriptManager.

Categories

Resources