1

I have following code .

In asp.net , I set session variable .Then pass it to javascript for modification . In javascript I can read session variable value and return modified value in TextBox1 . In asp.net again , I receive modified session variable value and store it in session variable .

protected void Page_Load(object sender, EventArgs e)
{
    Session["MyTest"] = "abcd";

    String csname = "OnSubmitScript";
    Type cstype = this.GetType();

    // Get a ClientScriptManager reference from the Page class.
    ClientScriptManager cs = Page.ClientScript;

    // Check to see if the OnSubmit statement is already registered.
    if (!cs.IsOnSubmitStatementRegistered(cstype, csname))
    {
        string cstext = " document.getElementById(\"TextBox1\").value = getMyvalSession()  ; ";
        cs.RegisterOnSubmitStatement(cstype, csname, cstext);
    }

    if (TextBox1.Text.Equals("")) { }
    else {
          Session["MyTest"] = TextBox1.Text;
    }

}


   <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">

<script language=javascript type="text/javascript">
    function getMyvalSession() {

         var txt = "efgh";
         var ff = '<%=Session["MyTest"] %>' + txt;
         return ff ;
    }
</script>

</head>
<body>

<form id="form1" runat="server">
<div>
    <asp:TextBox ID="TextBox1" runat="server"  AutoPostBack=true ></asp:TextBox>
 <input type="submit"  value="Submit" />
</div>
</form>
</body>
 </html>

But my aim was – Within javascript function itself I should be able to modify session variable . And I don’t want to use submit button.

0

3 Answers 3

2

Using cookie i can preserve value . Submit button is also not required . So this code has solved my purpose .

 <script language="javascript" type="text/javascript">

function writeCookie(name,value,days) {
    var date, expires;
    if (days) {
        date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        expires = "; expires=" + date.toGMTString();
            }else{
        expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}


function readCookie(name) {
    var i, c, ca, nameEQ = name + "=";
    ca = document.cookie.split(';');
    for (i = 0; i < ca.length; i++) 
       {
            c = ca[i];
            while (c.charAt(0)==' ') {
                c = c.substring(1,c.length);
            }
            if (c.indexOf(nameEQ) == 0) {
                return c.substring(nameEQ.length,c.length);
            }
       }
    return '';
}


function restore(){
    var sId = readCookie('sessionId');
    document.getElementById("TextBox1").value = sId ;
}


function backup() {

      var sId = document.getElementById("TextBox1").value;
      writeCookie('sessionId', sId, 3);
}


function getMyvalSession() {
            var ff = "Loading Value";
           return ff;
}


function TextBox1_TextChanged() {
          backup();
}


</script>








<body onload="restore()">

    <form id="form1" runat="server">
    <div>

         <asp:TextBox ID="TextBox1" Name="TextBox1" runat="server" 
          AutoPostBack="True" onchange="TextBox1_TextChanged()" ></asp:TextBox>

    </div>
    </form>
</body>


    protected void Page_Load(object sender, EventArgs e)
    {
         Loading();
    }


    void Loading (){

        String csname = "OnSubmitScript";
        Type cstype = this.GetType();

        // Get a ClientScriptManager reference from the Page class.
        ClientScriptManager cs = Page.ClientScript;

        // Check to see if the OnSubmit statement is already registered.
        if (!cs.IsOnSubmitStatementRegistered(cstype, csname))
        {
            string cstext = " document.getElementById(\"TextBox1\").value = getMyvalSession()  ; ";
            cs.RegisterOnSubmitStatement(cstype, csname, cstext);
        }


       }
Sign up to request clarification or add additional context in comments.

1 Comment

Sunny answered your question correctly and should have the accepted answer.
1

No, session variables cannot be modified on client side directly and expect to change on server. Atleast, AJAX request has to be made to persist the session value.

And based on your current code, I am not understanding significance of session variable. You're just appending text box value with session variable and submitting the form.

So, it would be direct statement without needing client side script, i.e,

//page_load
{
   Session["Mytest"] = test;
}

//page_submit
{
   Session["Mytest"] += txtName.text;
}

2 Comments

Instead of session variable , can i use Cache , cookie or viewstate . See , I just want to preserve value when user is entering text in textbox and even if user press f5 , value should not lost.
On textbox onblur event, call ajax method to store the modified value in session.
0

You can define a web method in asp.net or action in MVC and set session inside it from parameter passed

[HttpPost]
public bool SetSessionAction(string param)
{
   Session[sessionName] = param;
   return true;
}

then call method or action using $.ajax or $.post from jquery.

var paramValue = 'some data';
var targetUrl = "@Url.Action("SetSessionAction", "ControllerName" )";
        $.ajax({
            type: "POST",
            cache: false,
            dataType: "json",
            url: targetUrl,
            data: { param: paramValue },
            success: function (s) {
              alert('Set Session is: ' + s);
            }
        });

Good Luck

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.