Create javaScript variable in code behind of asp.net - asp.net

How do I register a Javascript variable on the server side (backend) and access it on the client side (Javascript file), without a hidden field, Literal, etc.?

You can use the RegisterClientScriptBlock-Function from the Page's ClientScriptManager.
Page.ClientScript.RegisterClientScriptBlock(Page.GetType, "initMyClientVariable", "var myClientVariable=null;", True)
EDIT: according to your new informations, that you want to register a client array, use ClientScriptManager's RegisterArrayDeclaration Method.
VB.Net example:
Dim myArrayValue As String = """1"", ""2"", ""text"""
Page.ClientScript.RegisterArrayDeclaration("myClientArray", myArrayValue)
According to the new information in my comments that you need access to that variable from an external js-file: you should pass the js-array as argument to the function in the js-file. For example:
callFunctionInJsFile(checkBoxes);

You can put the following code in .aspx file ...
<script type="text/javascript" >
var date1 = "<%: DateTime.Now %>";
var date2 = "<%= DateTime.Now %>";
</script>
<%: %> works under ASP.NET 4

You can put a literal in the xml portion of the code and assign that literal some text:
myLiteral.Text = "<script language=\"javascript\">var myVar = 24;</script>";
This makes myVar globally available on the client side once it's rendered. You can also use the ClientScriptManager object to use Asp.Net to inject scripts and variables.

First place an <asp:Literal ID="Literal1" runat="server"></asp:Literal> tag in the <head> of your .aspx file. Then in the server side code in your .aspx.cs file, do something like Literal1.Text = "<script type=\"text/javascript\">var timer = 3600</script>" and you've got yout javascript variable called timer.
That's it. Have fun!

Related

Setting session value in aspx page

I want to assign some value to a session variable via JavaScript in my aspx page.
var name = e.object.text;
<%# Session["CurrentName"] = name %>
Above code is giving following error:
Compiler Error Message: CS0103: The name 'name' does not exist in the current context
When I googled all the post are about getting the value from session in JavaScript. But I want to set the value to a session variable in JavaScript code.
How can I assign value to session variable in JavaScript?
Thank you
Accessing & Assigning the Session Variable using Javascript:
See Here
Assigning the ASP.NET Session Variable using Javascript:
<script type="text/javascript">
function SetUserName()
{
var userName = "Shekhar Shete";
'<%Session["UserName"] = "' + userName + '"; %>';
alert('<%=Session["UserName"] %>');
}
</script>
Accessing ASP.NET Session variable using Javascript:
<script type="text/javascript">
function GetUserName()
{
var username = '<%= Session["UserName"] %>';
alert(username );
}
</script>
Hope this helped you...! :)
You can't, at least not like this.
JavaScript is client-side thus rendered after the server-side (C#). That means you can't assign session values directly through JavaScript.
One way to solve your problem would be to use AJAX to asyncronously send a request to server and change value of the session.
Example how to do it.
<script runat="server">
var name = e.object.text;
Session["CurrentName"] = name;
</script>
Try this, by using runat="server" on script you can assign value to the Session

How to pass value to javascript from code behind page?

I have web application where i want to call one method on body onload method.
I have method like this
<body id="pageid1" onload="SetupFeaturedProperty(1,['http://www.brightlogic-estateagents.co.uk/MRUS/upload/918-1.jpg', 'http://www.brightlogic-estateagents.co.uk/MRUS/upload/918-2.jpg', 'http://www.brightlogic-estateagents.co.uk/MRUS/upload/918-3.jpg', 'http://www.brightlogic-estateagents.co.uk/MRUS/upload/918-4.jpg']);SetupFeaturedProperty(2,['http://www.brightlogic-estateagents.co.uk/MRUS/upload/665-1.jpg', 'http://www.brightlogic-estateagents.co.uk/MRUS/upload/665-2.jpg', 'http://www.brightlogic-estateagents.co.uk/MRUS/upload/665-3.jpg', 'http://www.brightlogic-estateagents.co.uk/MRUS/upload/665-4.jpg']);SetupFeaturedProperty(3,['http://www.brightlogic-estateagents.co.uk/MRUS/upload/38-1.jpg', 'http://www.brightlogic-estateagents.co.uk/MRUS/upload/38-2.jpg', 'http://www.brightlogic-estateagents.co.uk/MRUS/upload/38-3.jpg', 'http://www.brightlogic-estateagents.co.uk/MRUS/upload/38-4.jpg']);SetupFeaturedProperty(4,['http://www.brightlogic-estateagents.co.uk/MRUS/upload/122-1.jpg', 'http://www.brightlogic-estateagents.co.uk/MRUS/upload/122-2.jpg', 'http://www.brightlogic-estateagents.co.uk/MRUS/upload/122-3.jpg', 'http://www.brightlogic-estateagents.co.uk/MRUS/upload/122-4.jpg']);SetupFeaturedProperty(5,['http://www.brightlogic-estateagents.co.uk/MRUS/upload/1076-1.jpg', 'http://www.brightlogic-estateagents.co.uk/MRUS/upload/1076-2.jpg', 'http://www.brightlogic-estateagents.co.uk/MRUS/upload/1076-3.jpg', 'http://www.brightlogic-estateagents.co.uk/MRUS/upload/1076-4.jpg']);">
And the arguments of these method can be change in after some time.
I want to pass the argument when my page is loaded.
I have tried lot of method to pass the argument from code behind page to this page but it's not working.
Please let me know a better solution for this.
Thanks
use this:
Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript",getScript(),true);
and then:
private string getScript()
{
return "SetupFeaturedProperty(etc,etc,etc);";
}
If you are using UpdatePanels use the ScriptManager class instead of Page.ClientScript
There are multiple ways to do this. You can register the scripts using the RegisterClientScript method. You can make the body tag a server control and set it's onload attribute in the code behind or you can use Literal tag. However the method I find most clean is creating a JS variable and assigning it's value with a serverside code then using this variable in your JS code:
<script> var someVariable = <%= SomeProperty %>;</script>
Make sure that you define properties in your page and not move all your code behind in the markup.
Another good approach is to define a function for your event that takes the element as an input (pass this as the argument) and then attach the actual arguments as different attributes to the element.
<body runat="server" id="body" onload="onLoad(this)" data-someArg="someValue">...
You can set the attributes from your code behind like this
body.Attributes["data-someArg"] = "someValue";
This will be invalid in HTML4 but will work fine in all browsers and it will be valid in HTML5 as long as you prefix the attribute name with data-
Use ClientScript.RegisterStartupScript. Check MSDN:
MSDN - Javascript and ASP.NET 2.0
MSDN - ClientScript.RegisterStartupScript
One way to do it is to setup a Literal tag in your javascript. For example:
function somemethod()
{
var number1 = 10;
var number2 = <asp:Literal ID="litNumberFromCode" runat="server"/>;
alert(number1 + number2);
}
Then in your code behind access that control like any other:
litNumberFromCode.Text = 15;
Try using inline c# <% %> with your values printing

JavaScript question

calling a js function using onclick...
onclick="SubmitAge(66, 'ctl00_MainContent_arTo_upAgeRange')"
function just calls an updatePanel from the client... but its saying object expected at the onclick= part!!!
here is the function, is there anything wrong with the code?
function SubmitAge(age, UpdatePanelID) {
$get('HiddenAge').value = age;
__doPostBack(UpdatePanelID);
}
EDIT: THE SUBMITAGE FUNCTION IS INSIDE A .JS FILE (AGERANGE.JS) AND ONLY WHEN MOVED HERE DOES IT STOP WORKING: HERE IS THE LINKING METHOD/HEADERS FROM THE ASCX USERCONTROL INWHICH IT IS ALL CONTAINED...
%# Control Language="VB" ClassName="AgeRange" %
%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="AjaxCT" %
script src="AgeRange.js" type="text/javascript" /script
(arrow tags removed here as it wont display, hint: stackoverflow!!!)
im printing it like this from the server...
Public Sub AppendToSB(ByRef sb As StringBuilder, ByVal CurNo As Byte, Optional ByVal clickedNo As Byte = 0)
Dim sConfirmClick = ""
If clickedNo = CurNo Then ' maybe dont make it clickable...
sConfirmClick = "return confirm('The number " & CurNo.ToString & " is already selected, are you sure you want to select it again?');"
End If
sb.Append("<a href=""#"" onclick=""" & sConfirmClick & "SubmitAge(" & CurNo.ToString & ", '" & upAgeRange.ClientID &
"')"" runat=""server"">" & CurNo.ToString & "</a>")
End Sub
Complete rewrite of my post after several clarifications:
The problem is that the ASPX page is referencing an ASCX user control that is located in a different folder. That ASCX control has an HTML <script> tag that is using a relative path to the JS file.
The solution is to correctly resolve the URL to the JS file by using some extra code:
<script src="<%= ResolveClientUrl("MyScriptLibrary.js") %>" type="text/javascript">
</script>
To prevent the script file from being referenced multiple times I recommend using the approaches specified in this other post:
ASP.NET dynamically insert code into head
Here's what it looks like in the user control's code:
// Register a script reference:
Page.ClientScript.RegisterClientScriptInclude(GetType(), "myLibraryScript", "~/Scripts/MyScriptLibrary.js");
here is how i decided to do it, ResolveClientURL is important, static link will not always work, also the if check will prevent the script being added several times in one page if you use the control multiple times on same page...
If Not Page.ClientScript.IsClientScriptIncludeRegistered("AgeRangeJS") Then ' no point in registering it twice!
' AND its registered in the header, where it should be, not two copies in the body :)
Page.ClientScript.RegisterClientScriptInclude("AgeRangeJS", ResolveClientUrl("AgeRange.js")) ' ResolveClientUrl("AgeRange.js")
End If

<%# server tags in jquery

I am very new to jQuery and have got a quick question.
I wish to use my server side classes in my jQuery code, something similar to this:
$(document).ready(function() {
var temp = <%# myClass.Id %>;
})
Is this possible? if so, how?
Thank you very much
This is the later question I refined my former question to:
I'm sorry, I think I didn't explain myself too well... I've got a class name User. It's a class I built in my business logic.
I've got a web page named UserProfile, inside it I've got the following property exposing the current logged in user:
public BL.User CurrUser { get { return (BL.User)Session["currUser"]; } }I want to be able to access this User class from my aspx page using Jquery. How do I do that?
The databinding syntax
<%# MyStaticClass.MyProperty %>
will only work if you call DataBind on the container (page). What you're after is most likely the following syntax:
<%= MyStaticClass.MyProperty %>
which will also give you access to you page / control members
<%= this.MyPageProperty %>
As was already mentioned you should really assign those values to java script variables and pass those variables to you JS functions.
This will only work if your javascript is embedded in your source files (e.g. the .aspx files):
<script type="text/javascript">
var id = <%# myClass.Id %>; // store as raw value
var id_string = '<%# myClass.Id %>'; // store in a string
</script>
As others have said, if the JavaScript is in your aspx page, then using server tags will work fine.
If you have your jQuery in an external script file, then you could put this in your aspx page
<script type="text/javascript">
var myClass = $('#<%= myClass.ClientID %>');
</script>
and then use the variable in your external script file
$(function() {
myClass.click( function() { ... });
});
For other options take a look at this question and answer - How to stop ASP.NET from changing ids in order to use jQuery

Programmatically adding Javascript File to User Control in .net

How do you add Javascript file programmatically to the user control?
I want the user control to be a complete package - ie I don't want to have to add javascript that's related to the user control on the page where it's used, when I can do it inside the control itself.
Since there is no Page object in the user control, how would you do it?
In the Page_Load method of control.ascx.cs file:
LiteralControl jsResource = new LiteralControl();
jsResource.Text = "<script type=\"text/javascript\" src=\"js/mini-template-control.js\"></script>";
Page.Header.Controls.Add(jsResource);
HtmlLink stylesLink = new HtmlLink();
stylesLink.Attributes["rel"] = "stylesheet";
stylesLink.Attributes["type"] = "text/css";
stylesLink.Href = "css/mini-template-control.css";
Page.Header.Controls.Add(stylesLink);
This will load css and Javascript into the head tag of the main page, just make sure that the head has runat="server".
You can register client script includes using the ClientScriptManager.
Page is accessible through the Control.Page property.
Page.ClientScript.RegisterClientScriptInclude (
typeof ( MyControl ), "includeme.js", "js/includeme.js" );
EDIT: Sorry, for a total "complete package", its possible using scripts as Embedded Resources,
and aquire dynamic URL's through the WebResource.axd handler.
If this is not considered totally complete, then i guess it could be put in App_LocalResources, but it never gonna be just one file,
unless the code and script is inline.
The same as gnomixa's response, only a bit cleaner:
HtmlGenericControl js = new HtmlGenericControl("script");
js.Attributes["type"] = "text/javascript";
js.Attributes["src"] = "jscript/formfunctions.js";
Page.Header.Controls.Add(js);
from http://www.aspdotnetfaq.com/Faq/How-to-Programmatically-add-JavaScript-File-to-Asp-Net-page.aspx
In my site I Place all needed scripts and styles to placeHolder
<asp:placeHolder runat="Server" ID="phHead">
<script src="/header/widget/script.js" type="text/javascript"></script>
<link href="/header/widget/style.css" rel="stylesheet" type="text/css" />
</asp:placeHolder>
and
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Page.Header.Controls.Add(phHead)
End Sub
Good question!
A UserControl should be a single package without any dependency on a JavaScript or a CSS file. You will need to make the JS and CSS files as embedded resources. Right click properties and set build action to embedded resources. Then you need to inject the JavaScript and CSS files as WebResources.
Here is one article that I wrote yesterday which talks about the same scenario:
http://highoncoding.com/Articles/502_Creating_RadioButton_Validation_Using_Custom_Validator.aspx
I generally do it when rendering the HTML for the control and depending on whether it's a library injection or an instance injection I use the Items collection to specify whether or not I have already produced the code for a control of this type during the current request using a unique identifier.
Something to the effect of:
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
//Check if the Object Script has already been rendered during this request.
if (!Context.Items.Contains("xxx"))
{
//Specify that the Object Script has been rendered during this request.
Context.Items.Add("xxx", string.Empty);
//Write the script to the page via the control
writer.Write([libraryinjection]);
}
//Write the script that instantiates a new instance for this control
writer.Write([instanceinjection]);
}
If you have the text of the actual javascript in your .CS file, you can call Page.ClientScript.RegisterClientScriptBlock.
The following assumes that "GetScript()" returns the actual javascript you want added to the rendered control.
Page.ClientScript.RegisterClientScriptBlock(GetType(), "controlScriptName", GetScript());
I found this to be a more elegant way to fix-link to your javascript.
In your .ascx, link to your script files the following way:
<script src='<%= ResolveClientUrl("~/Scripts/jquery-1.7.1.min.js") %>' type="text/javascript"></script>
<script src='<%= ResolveClientUrl("~/Scripts/jquery.maskedinput-1.3.min.js") %>' type="text/javascript"></script>
That way, no matter which subfolder/page you add your user control to, the link to your scripts will always be correctly resolved.

Resources