How to pass data from SQL Server to jQuery var [Flot] - c#

I have two columns of data in an Database on MS SQL Server. One is datetime variable and another is an int.
Im trying jQuery and Flot to plot the datetime vs int.
I can programatically get the data from SQL Server using C#. But how do I pass it to the JavaScript File which has the vars for flot?

If you want to call a script in a loaded html document, you can use the Invoke method from the appropriate HtmlDocument or WebBrowser object to call a javascript function within that page, for example:
http://msdn.microsoft.com/en-us/library/system.windows.controls.webbrowser.invokescript.aspx

I am unsure how you would pass the data from c# to a *.js file in your case, I dont think its possible. But you could try a hack on the page that contains the *.js include you could try declaring and setting the javascript variable to the c# code (so in the ASPX, if its ASP.NET) and then putting the *.js include reference after that point and in it not re-declaring the variable but using it. You can also use JSON or AJAX to call server side code and return values and execute code.
Scenario 1: (The hack way, which is not clean and hard to maintain but does the job)
File.aspx
<script language="javascript" type="text/javascript">
var MyVariable = "<%=C_Variable_On_Code_Behind%>";
</script>
<script type="text/javascript" src="/scripts/YourJsFile.js" >
</script>
YourJsFile.js
if(MyVariable != null && MyVariable.length > 0){
//Do some thing.
}
Scenario 2: (JSON, AJAX, JQUERY UI)
jquery ui sample for a autocomplete: try this link
Another example: Or this link
Scenario 3: (Writing to the client from server-side c#)
Use RegisterStartupScript or RegisterClientScriptBlock via the ClientScriptManager object, here is a dummy code I put together so you can look them up and have an idea so you can find out more, this is not meant to be full code.
ClientScriptManager script = Page.ClientScript;
if (!script.IsClientScriptBlockRegistered(this.GetType(), "YourLabelForThis"))
{
script.RegisterClientScriptBlock(this.Page.GetType(), "YourLabelForThis",
"<script type=\"text/javascript\">var MyVariable = "Dummy text";</script>", false);
}
Please note you have to place the js code as an include or further code in the right position in the page whther you want it before or after this code, so lookup RegisterStartupScript or RegisterClientScriptBlock via the ClientScriptManager. To see where your code will be placed and how you should handle it. Also look at the page source in your browser to also see it.

Related

How do i pass an array from .cs file to .aspx

I have a webform called "Home.aspx".
In Home.aspx.cs, I created an array called myArray.
I want to use this array in Home.aspx to generate a word cloud.
something like below:
<script>
$('#wordcloud').jQCloud(myArray,{shape: 'rectangular'});
</script>
Can someone help me in solving this.
First, you don't want to put the C#-generated array onto your aspx page, because that array is a C# object, and javascript needs to be sent as text. You want to put a string output of the array onto the page. So you should create a string as a protected property in your code behind, and put the string of the array into that.
Then, on the front end, you can write the protected property onto the page with <%= myString %>
There are a couple of ways to achieve it.
Let server side code generate the whole JavaScript for you, which
means you will need to construct the JS code as a string in the
code-behind (.aspx.cs page) then use
ClientScriptManager.RegisterStartupScript method to register it so
that JS code will be executed when page loads.
Use server side script tag on your ASPX page. It's like point 1 but you write server side code on your front page.
Apply JS serialization and let the serialiser generate the JS array for you.
Below is an example of using a serialization approach.
<%
// create you array here
var myArray= new string[]{"apple", "orange"};
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
%>
Then what you need is to place above code on your ASPX page, before your JavaScript code block.
<script>
var myJsArray = <%= serializer.Serialize(myArray) %>;
$('#wordcloud').jQCloud(myJsArray, {shape: 'rectangular'});
</script>
One thing to remember though, the server side array object and client side javascript array are two different things. The serialization/deserialization is required to allow data/array of data to be passed between browser and web server.

pass a c# variable to javascript function

I'm trying to pass a c# variable as an argument to a java-script function like
<%var count=model.SomeMode.Count();%>
when i pass it to my java script function "checkAll(count)" it does not fire but without the argument its workin fine
CheckAll
Remember the page gets created however you wish. So, you could do something like:
<script type="text/javascript">
var count = <%=model.SomeMode.Count(); %>;
</script>
You could apply the same logic in method calls, so you could do:
CheckAll
Javascript can't see your C# source directly - you need to write it into the Javascript source on the server side:
CheckAll
It should look like this:
<script type="text/javascript">
var count=<%=model.SomeMode.Count()%>;
</script>
Currently you're declaring your variable in C#, not outputting it in the page as a JavaScript one. Instead, you want to declare var count literally in the page and have it set to the output of model.SomeMode.Count().
This might be good for your solution:
<a href="#" onclick='return checkAll(<%=count%);'>CheckAll</a>
But there is an other way of doing this instead of conventional way:
Sharing Variables Between JavaScript and C# by Fredrik Kalseth

Reading C# property into JQuery code

I'm trying to read the value of a C# property from my code behind file into some JQuery script (see below). The JQuery selector I've written accesses an ASP.Net GridView and then a CheckBox field within the gridview. Whenever a checkbox is checked or un-checked the code is hit, but I need to access the C# property from the code behind to take the appropriate action based on the value of the property.
$(".AspNet-GridView-Normal > td > input").click(function() {
//Need to access the C# property here
//Take action here based on the value of the C# property
});
This may be stating the obvious, but the code behind doesn't exist on the client side where your jQuery code is executing. What you could do is assign the value of the property to a hidden field on the server side so that when you need to check it with jQuery on the client side it will be available. So you might do the following on the client side.
Markup:
<asp:HiddenField ID="hfValueINeedToKnow" runat="server"/>
Code Behind:
hfValueINeedToKnow.Value = <some value>;
jQuery:
$("#<%= hfValueINeedToKnow.ClientID %>").val();
You might need to make some minor changes to support a value for each row of the grid, but hopefully this explains the general idea.
You mentioned in a comment that the value is an int. And I see it's also a public property in your codebehind. This is trivial now - you don't need to escape the value, nor access it in some round-about way, and you get type safety for free:
<script>
$(".AspNet-GridView-Normal > td > input").click(function() {
var AvailableInstalls = <%= AvailableInstalls %>;
});
</script>
Well you can't.
You need to render the C# property in some element (perhaps a hidden field) and then look at it that way.
But explain further: What property are you trying to check?
What I've done for this scenario in the past is to print out my code value into the markup and store whatever it is in a javascript variable, thus making a copy of it available to client-side code. This is a silly example, but hopefully it makes sense:
<%
var messsge = "Hello World!"
%>
<html>
<head>
<script type="text/javascript">
function ShowMessage()
{
var msg = '<%= message %>';
if(msg)
alert(msg);
}
</script>
</head>
</html>
There isn't a really clean way to do this. Your best bet would probably be to use the ClientScript.RegisterClientScriptBlock functionality built into ASP.NET. Here's a good primer.
private int myValue;
protected void Page_Load(object sender, EventArgs e) {
ClientScript.RegisterClientScriptBlock(typeof(Page),
"vars", "<script>var myParams = { p1: " + myValue + ", p2: 'My Name' };</script>");
}
This will put the supplied script on your page towards the top of the form. You can change that too. Obviously, it isn't the prettiest; you are essentially string concatenating a different language, but it will work, and for simple variable declaration isn't too rough on the eyes.
ASP Embedded in JavaScript always makes me nervous from the perspective of script injection attacks and the inability to unit-test your JavaScript.
This build upon an ealier answer:
<script type="text/javascript">
$(".AspNet-GridView-Normal > td > input").click(function() {
var AvailableInstalls = $("#MyHidden").val();
});
</script>
You could move it to a hidden variable:
<input type="hidden" id="#MyHidden" value="<%= AvailableInstalls %>" />
However this doesn't get around the problem of injection. So you could you could add a server-side hidden variable and set it from the Page_Load event function in ASP.NET.
(P.s. you also need the attribute type="text/javascript" in your script tag to make it valid HTML).
If you will put your value into an asp:HiddenField with id hfValueINeedToKnow, the simplest way to retrieve this value client side is
var jsvar = $("[id$=hfValueINeedToKnow]").val();
So you can also place this code in a separate .js file.

Methods for dynamically building JavaScript within an ASPX page?

I have a page that is referenced via a <script> tag from a page on another site. In the script src, I pass in the form I want my script to build (from a db table), and the div where the dynamically built form should go. The calling page looks something like this:
<div id="FormContainer"></div>
<script type="text/JavaScript" src="http://www.example.com/GenerateForm.aspx?FormId=1&div=FormContainer"></script>
GenerateForm.aspx contains the code that reads the QueryString parameters for the FormId, and the Div Id, and outputs JavaScript that will build the form.
My question is this. What are the different methods for "outputting" the JavaScript? Some of the JavaScript is static, and can be packaged into an external .js file and I have jQuery too. But should I add that on the GenerateForm.aspx markup page? Or should I use a ScriptManager?
And what about the dynamically built JavaScript? Currently I'm just using Response.Write() for a proof of concept, but instead, should I be doing something else? Use a Literal control on the page and set its value? Use a ScriptManager? Something else?
I know this is a verbose question, so thanks in advance!
If you want to use a seperate, referenced Javascript file, you probably want to do is use an ashx file. Basically this is just a generic handler that you'll use to write directly to the output stream without having to deal with the ASP.NET page lifecycle. If you add a basic Generic Handler (.ashx) to your site from the Add New Item dialog, the template should be enough direction, using context.Response.Write() to output your Javascript dynamically.
The ScriptManager is more useful if you want to output individual lines of Javascript to be ran at certain times, like after an event has fired. Then you can do ScriptManager.RegisterClientBlock(this, this.GetType(), "CodeBlock", "alert('Button clicked');", true); to show a client alert box after a button has been clicked, for example.
Static files should be handled just that way - statically. The server can handle the caching, and does not cause unnecessary processing if you reference the static script file directly from the script tag. However, if you need to load a static script dynamically, you could, for example, create a literal that had the <script> tag inside it. This way it uses the browser's cached version of the static file.

Diff RegisterClientScriptBlock & RegisterStartupScript & responce.write("script")

i need individual explanation and individual advantages regarding RegisterClientScriptBlock & RegisterStartupScript & responce.write("script");
i got some information like
RegisterClientScriptBlock() methods will inject the script after the form open tag but before page controls
RegisterStartupScript() methods will inject the scripts after page controls but before form close tag.
we can also simply wrie responce.write("script") it aslo include the script.
but i need individual explanation
if any link is available regarding this topic also pls reply me.
If you use the RegisterClientScriptBlock() and you need to reference other javascript methods or html objects that may get injected, you run the risk of them not being created when the script is run. Using the RegisterStartupScript(), as you said, puts the script at the bottom of the page, garanteeing that all objects will have been rendered and created before your script is run.
If you are using either to add a script that is a function like:
<script type="text/javascript>
function myFunc(){
...
}
</script>
Then is doesn't matter, because that function needs to be called explicitly, by something else.
But if you are trying to have a script run after the document loads like:
<script type="text/javascript>
doStuff();
</script>
Then you should use RegisterStartupScript() so you are garanteed that any objects called by you or the functions you call exists.

Categories

Resources