Setting session value in aspx page - asp.net

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

Related

how to get javascript calender value on server side

I am new on Asp.net. I am using Javascript calender It use Input tag.if I use runat="server" so that I can get value on cs page then it does not display calender. How can I get calender value from input tag to .cs page
Simplest way:
Have a hidden field on your control.
Set its in javascript by using :
$('#<%=hdDate.ClientID %>').val("date value here");
and then you can access this hidden field in cs file.
create a hidden field as in your aspx page which should be runat="server".
then
On button click call javascript function say jsOnclikfun() and write this function as
<script type="text/javascript">
function jsOnclikfun() {
var dateInputtext = document.getElementById("Id Of input textbox which you are trying to make runat=server");
var hdDateValue = document.getElementById('<%= hiddenField_Id.ClientID %>');
hdDateValue.value = dateInputtext.value;
return true;
}
</script>
Now on server side where ever you need data get it from that hidden field as hiddenfieldID.Value.
Hope this helps.

asp.net methods in javascript

I have a website
I need to find the id of my selected profile and assign that value to a variable in javascript
and show that in an alert box
where should i write the function which javascript needs to call
in the app_code folder'class
or a web page's code file
var some_variable = '<%=the_method() %>';
I'm going to assume ASP.NET WebForms and not MVC...
if you have in your page.aspx a variable named:
public string myProfile = "profile1";
you will be able to pick that up in your HTML just like anything else:
<% Response.Write( myProfile ) %>
in javascript you can do the same:
<script>
var myProfile = '<%= myProfile %>';
</script>
You can also call methods:
in your page.aspx
public string getUserName() {
return String.Format("{0} {1}", User.fname, User.lname);
}
in your javascript
<script>
var myProfile = '<%= getUserName() %>';
</script>
Remember that you need to decorate your variables and methods publicly, as if not, by default they will be private and not accessible from outside the scope of your code behind file.
You should use Webservices or Webmethods to communicate with the server side methods from your JavaScript code

Create javaScript variable in code behind of 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!

asp.net mvc c# javascript web.config

i want to have retrieve a "imagetype" from appsettings in my web.config in javascript . how can i do that?
You can use following code in your page markup:
<script language="JavaScript" type="text/javascript">
var type = '<%= ConfigurationManager.AppSettings["imagetype"] %>';
</script>
Use the following:
var value = System.Configuration.ConfigurationManager.AppSettings["imagetype"];
You may find that for it to work you need to add a reference to System.Configuration.dll if you don't already have one.
Create a new page, and in Page_Load put the line so that it all reads:
Response.Clear();
var value = System.Configuration.ConfigurationManager.AppSettings["imagetype"];
Response.Write(value);
Response.End();
You can now make an AJAX call to the page from Javascript, perhaps using ExtJs and the text will be returned to your javascript.
Alternatively, you could put the following into your page:
<script language="javascript" type="text/javascript">
var appSettingValue = '<%=System.Configuration.ConfigurationManager.AppSettings["imagetype"]%>';
// The variable "appSettingValue" will contain the string from your web.config
alert(appSettingValue);
</script>

<%# 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

Resources