How do you set a session variable in JavaScript? - javascript

Can this be done with a PageMethods call? I need to save some variables in a control so that they can be used by a control on another page at a later time. Is there a way to do this via JavaScript?

Sounds like you need cookies, localStorage, or sessionStorage.

You can use JS to change the values in a hidden field, and capture them on the postback, which personally I think preferable to cookie usage if the value is only needed for the life of the current session.

It's a very bad idea to do this with PageMethods.
You can add a generic handler (*.ashx) and then do a XMLhttpRequest to this URL, passing it parameters.
Note that the ashx handler needs to inherit from IRequiresSessionState, in order to access a session.
You can also get a session value that way.
Like this:
using System.Web;
using System.Web.SessionState;
public class Handler : IHttpHandler , IRequiresSessionState
{
public void ProcessRequest (HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
string item = context.Request.QueryString["item"] ?? "";
string update = context.Request.QueryString["update"] ?? "";
switch (item)
{
case "A":
if (!string.IsNullOrEmpty(update))
context.Session["A"] = update
object a = context.Session["A"];
context.Response.Write(a != null ? (string) a : "none");
break;
case "B":
if (!string.IsNullOrEmpty(update))
context.Session["B"] = update
object b = context.Session["B"];
context.Response.Write(b != null ? (string) b : "none");
break;
}
}
public bool IsReusable
{
get { return false; }
}
}
See my post here for XMLhttpRequest:
Why does this JavaScript code ignore the timeout?
You might want to add a parameter no_cache=TIME_IN_MILLISECONDS, in order to beat browser caching.

I like to do it the following way:
javascript:
function SendData(data) {
var postbackarg = "#####" + data;
__doPostBack("txtTest", postbackarg);
}
VB In Page_Load event:
If Me.IsPostBack Then
Dim controlName As String = Request.Params.Get("__EVENTTARGET")
Dim args As String = Request.Params.Get("__EVENTARGUMENT")
ProcessUserInterfaceData(controlName, args)
If (controlName = "txtTest" AndAlso args.IndexOf("#####") = 0) Then
args = args.Substring(5, args.Length - 5)
'args now = data from the UI
End If
End If
This started from an example I found somewhere else. I cannot find it.. The only purpose for the 5 '#' is to identify the postback as coming from SendData.

Session variables cannot be set using Javascript directly
But you can use the following code to set session variables in aspx page
<%Session["SESSION VARIABLE NAME"] ="SOME STRING"; %>
You can check the same variable using an alert in javascript
alert('<%=Session["SESSION VARIABLE NAME"] %>');
Yes session variable can be set using Pagemethods using the below way
declare the below code in aspx.cs page
[WebMethod]
public static void functionname(string st)
{
Home h = new Home();
System.Web.HttpContext.Current.Session["SessionUserName"] = st;
h.strUserName = (string)System.Web.HttpContext.Current.Session["SessionUserName"];
}
and call the function using pagemethod in aspx
PageMethods.functionname("HELLO");
this will set the session variable to HELLO
You can also make an ajax call to the webmethod if you dont want to use pagemethods.function!!

Related

How can I access Session variables in code-behind

In script I set Session.
<script>
$(document).on('click', '.Pagination', function () {
'<%Session["Pagination"] = "' + $(this).attr('id') + '"; %>';
alert('<%=Session["Pagination"] %>');
});
</script>
Alert works.
I can't access When i want to session from code-behind
if (!string.IsNullOrEmpty(Session["Pagination"] as string))
{
string Val = Session["Pagination"].ToString();
Session["Pagination"] = null;
}
String Val equal to ' + $(this).attr('id') + '
I used to put the value in the hidden variable and this will be accessible in code-behind, anyway the session object is active in code behind you can set the variable to session successfully.
Advantage:
Globally declared session strings are accessible in code-behind and you can use the variables by calling the property files
ASP
<asp:HiddenField id="session_obejct" runat="server" />
Javascript
document.getElementById('session_obejct').value = "Variable you want to set in session";
C#
session["SESSION_NAME"] = session_obejct.Value;
you can use other methods as well, I hope this will meet your requirement
I used this way and do it if one have better way pleas tell me
Javascript function:
<script>
$(document).on('click', '.Pagination', function () {
PageMethods.NumPagination($(this).attr('id'));
});
</script>
Code behind :
[System.Web.Services.WebMethod]
public static string NumPagination(string Num)
{
Page Pagination = new Page();
Pagination.Session["Pagination"] = Num;
return Num;
}
if (!string.IsNullOrEmpty(Session["Pagination"] as string))
{
string Select = "1";
Select = Session["Pagination"].ToString();
Session["Pagination"] = null;
}
LINK
You cannot write to the (server-side) Session from within client side code.
The alert('<%=Session["Pagination"] %>'); works because it is executed server side first, reading the value of Session["Pagination"] and inserting that into the javascript source, before sending that source to the browser.
By the time the browser sees that text and interprets it as javascript, the server-side commands (<% ... %>) have been replaced. The browser wouldn't know what to do with them anyway.

Need to force post back from Javascript not initiated by a button click

I need to use a JavaScript Confirm function in my ASPX pages to confirm various actions based on conditions in the C# code behind not directly connected to a button click event. E.g. if it is calculated that number of records > 200, ask 'Do you want to continue?' then based on Yes or No clicked perform relevant actions.
I have my JavaScript defined as:
<script type = "text/javascript">
function Confirm(val) {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm(val)) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
And call it from code behind and get the response using RegisterStartupScript and Request.Form like so:
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "confirm_value", String.Format("Confirm('{0}');", msgstr), true);
string confirmvalue = Request.Form["confirm_value"];
The Confirm box comes up, but the confirmvalue string is always "behind". That is, if I click 'Yes' on the Confirm box, it returns 'No'; but if I stay on the same page and execute the process a second time and click 'No', I get 'Yes' returned; and so on.
Question: How do I force postback of confirmvalue so I can access the response in code behind in a timely manner?
There can possibly be four ways by which you can achieve this with/without post back:-
Using AjaxMethod Attribute on a method in a code-behind file as below:-
[AjaxMethod(HttpSessionStateRequirement.ReadWrite)]
public object DoSomething(int countValue)
{
//Do Something
}
Then from the ascx file you will be able to call the method by executing the class name dot the method name. Here, in this case the method name is DoSomething.
In case you are using ScriptManager in your ascx file then you can enable page methods invocation by setting EnablePageMethods attribute of the Script Manager as true. But, the method you are invoking should be static. MSDN link
public static object DoSomething(int countValue)
{
//Do Something
}
Here, you will be able to call the method directly from your JS.
Using web service as follow:-
[ScriptService]
public class YourService
{
[WebMethod(EnableSession=true)]
public object DoSomething(int countValue)
{
//Do Something
}
}
Post back way:-
if (IsPostBack)
{
string ControlID = string.Empty;
if (!String.IsNullOrEmpty(Request.Form["__EVENTTARGET"]))
{
ControlID = Request.Form["__EVENTTARGET"];
Control postbackControl = Page.FindControl(ControlID);
}
}

Jquery submit adds flawed encoding [duplicate]

I want to send the variables itemId and entityModel to the ActionResult CreateNote:
public ActionResult CreateNote(
[ModelBinder(typeof(Models.JsonModelBinder))]
NoteModel Model, string cmd, long? itemId, string modelEntity)
with this javascript:
Model.meta.PostAction = Url.Action("CreateNote", new { cmd = "Save", itemId = itemId, modelEntity = modelEntity});
However, the url being send is
localhost:1304/Administration/blue/en-gb/Entity/CreateNote?modelEntity=Phrase&itemId=44
I want to send
localhost:1304/Administration/blue/en-gb/Entity/CreateNote?modelEntity=Phrase&itemId=44
How can I prevent Url.Action to put the & in front of the second variable that I want to send?
I didn't notice yesterday that you had & I thought that was the SO editor had changed that. Try wrapping your Url.Action() in a #Html.Raw() to prevent the Encode of &.
Or alternatively only Url.Action() the controller/action bit and pass the two parameters as post data rather than directly on the url, jQuery should sort out the &'s for you that way.
I think your problem is with Model.meta.PostAction - is that property a string?
If so then my guess would be that you're adding it to the page with either:
Razor: #Model.meta.PostAction
ASP view engine: <%:Model.meta.PostAction%>
Both of which automatically encode that string for you.
To fix it either use #Html.Raw()/<%= (both of which don't encode) or make the PostAction property an IHtmlString that knows that it's already been encoded:
string actionUrl = Url.Action("CreateNote", new { cmd = "Save", itemId = itemId, modelEntity = modelEntity});
Model.meta.PostAction = new HtmlString(actionUrl);

How to send a value from client side to server side for server side processing

I am trying to send a value from the client side using javascript or JQuery, to the server (ideally to a method in my codebehind). I am using C# .net 4.0.
In my client side JQuery I have:
$.post("test.aspx/testMethod",
{
name: "Donald Duck",
city: "Duckburg"
}
);
In my server side (test.aspx.cs) method, I have
public void testMethod()
{
string name = Request.Form("name");
string city = Request.Form("city");
}
But with this I get a compilation error: "Non-invocable member 'System.Web.HttpRequest.Form' cannot be used like a method."
How can I rectify this? Or reach the same objective? Using the $.ajax({...}) is not an option as the value is needed by a non-static method.
There is a very simple answer to this. After searching for hours thru dozens of questions posted along the same lines and many people offering overly complicated ajax post back solutions, I came up with this. Basically a one liner. Hope it helps someone:
In your javascript you just call the method:
PageMethods.SomeMethod('test');
Your "SomeMethod" would be a code behind method like this:
[WebMethod]
public static string SomeMethod(string param1)
{
string result = "The test worked!";
return result;
}
Rules:
You have to identify your code behind method with a WebMethod attribute. It has to be static. And you have to register a script manager in your page as follows:
<asp:ScriptManager ID="MyScriptManager" runat="server" EnablePageMethods="true" />
Since I am working with an aspx webforms page to do some really simple javascript functions like retrieving / stashing geo location, I put it inside the Form element as required.
you can use like this - https://rvieiraweb.wordpress.com/2013/01/21/consuming-webservice-net-json-using-jquery/
try it :)
I dont know if Web Forms support this type of JSON request. I have tried long back but I have to add asmx file that time. Currently you have WCF, but if you don't want to change your webforms project and still want restful api, then merge MVC project for your restful task. You dont have to shift everything but it work together. Here it is explained how?
I don't know about latest version of Web Forms but before VS2012, you can't do ajax type call to page. As far as I know.
Please let me know if any further details needed.
Found Solution... (Hope someone finds it useful)
JAVA SCRIPT
function myFunction() {
var str= "fname=Henry&lname=Ford";
log("MyString=" + str);
}
function log(message) {
var client = new XMLHttpRequest();
client.open("POST", "Default.aspx", true); // Default.aspx being the page being posted to
client.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
client.send(message);
}
C# Default.aspx.cs (CODE BEHIND TO Default.aspx)
protected void Page_Load(object sender, EventArgs e)
{
getText();
}
public void getText()
{
if (HttpContext.Current.Request.Form.Keys.Count > 0)
{
string code = HttpContext.Current.Request.Form["MyString"];
// code = "fname=Henry"
// For looping etc, see below
}
}
WHAT ELSE YOU CAN GET....
HttpContext.Current.Request.Form.Count // 2
HttpContext.Current.Request.Form.Keys.Count // 2
HttpContext.Current.Request.Form.AllKeys[0] // "MyString"
HttpContext.Current.Request.Form.Keys[0] // "MyString"
HttpContext.Current.Request.Form.AllKeys[1] // "lname"
HttpContext.Current.Request.Form.Keys[1] // "lname"
HttpContext.Current.Request.Form[0] // "fname=Henry"
HttpContext.Current.Request.Form[1] // "Ford"
Loop through keys...
foreach (string key in Request.Form.Keys)
{
DoSomething(Request.Form[key]);
}
The above code works in that it passes a value(s) from the client side javascript to the server side code-behind, but then unable to use the value because you lose it.
The following modification to the above code is required to use the value (essentially store it in a separate static class until needed).
C# Default.aspx.cs (CODE BEHIND TO Default.aspx)
protected void Page_Load(object sender, EventArgs e)
{
getText();
}
public void getText()
{
if (HttpContext.Current.Request.Form.Keys.Count > 0)
{
// Reset staticValue
Class1.staticValue = "";
Class1.staticValue = HttpContext.Current.Request.Form["MyString"];
// Call Class1.staticValue anywhere else and you get expected answer= "fname=Henry"
}
}
STATIC CLASS (App_Code/Class1.cs) - another object to store value (otherwise the HttpContext object removes it from anything)
public class Class1
{
private static string myValue = "";
public Class1()
{
//
// TODO: Add constructor logic here
//
}
public static string staticValue
{
get
{
return myValue;
}
set
{
myValue = value;
}
}
}

ajaxToolKit autoCompleteExtender OnClientItemSelected

I am trying to implement an autoCompleteExtender into my project. Currently I am using the OnClientItemSelected property to call a javascript on the client side. Is there a way (using another property or some other code) that will let me call a method in the code behind when the user selects an option?
function AutoCompleteEx_OnClientItemSelected(sender, args) {
__doPostBack(sender.get_element().name, '');
}
On server side handle TextChanged event of extended textbox.
For this you need to return the list from web service method with ID and Text
Here "lst" is the actual list with data from your data source.
List<string> items = new List<string>(count);
for (int i = 0; i < lst.Count; i++)
{
string str =AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(lst[i].Text,Convert.ToString(lst[i].IDValue));
items.Add(str);
}
return items.ToArray();
Then simple javascript
function GetID(source, eventArgs )
{
var HdnKey = eventArgs.get_value();
document.getElementById('<%=hdnID.ClientID %>').value = HdnKey;
}
and dont forget to set the attribute in auto complete extender
OnClientItemSelected="GetID"

Categories

Resources