batwing
batwing

Reputation: 247

How to set JavaScript variable to ASP.NET Session?

How can I set a JavaScript variable to an ASP.NET Session? Currently the value in the price is not stored in the session, instead it stores the string "'+price+'". How to store the price variable's value?

function getCheckboxVal(el)
{
    var price = el.getAttribute("Price");
    '<%Session["Price"] = "' + price +'"; %>';
}

Upvotes: 1

Views: 13438

Answers (3)

Bharati Mathapati
Bharati Mathapati

Reputation: 119

We cannot directly set clientside value to session. We can do this by using Hidden fileds

<asp:HiddenFieldID="hdPrice" runat="server" /> 

Further get this js price and set to variable hprice in javascript. This variable can be added into session

Session["PriceData"] = hdPrice;

Hope this helps you.

Upvotes: 0

Ambrish Pathak
Ambrish Pathak

Reputation: 3968

You can not directly set session from JS because session is stored on server and JS runs at client side.

You can use hidden inputs for this purpose like:

<input  type='hidden' id='Price' name='Price'/>

var price = el.getAttribute("Price"); //Populate price var as required
var h=document.getElementById('Price'); 
h.value=price; //set hidden input's value

Then get this var price to set the session from code behind like:

Session["TestSession"] = Request.Form["Price"];

Upvotes: 7

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

Since Session state maintained on server-side, it can't be assigned directly from client-side. You can perform an AJAX callback to a server-side web method which later stores session state value:

[WebMethod(EnableSession = true)]
public void SetPrice(string value) 
{
    if (Session != null)
    {
        Session["Price"] = value;
    }
}

function getCheckboxVal(el) {
    var price = el.getAttribute("Price");
    $.ajax({
        type: 'POST',
        url: 'Page.aspx/SetPrice',
        data: { value: price },
        success: function (data) {
            // do something
        }

        // other AJAX settings
    });
}

Or using hidden field with runat="server" attribute and assign its value to bring it into code-behind:

ASPX

<asp:HiddenField ID="HiddenPrice" runat="server" />

<script>
    function getCheckboxVal(el) {
        var price = el.getAttribute("Price");

        document.getElementById('<%= HiddenPrice.ClientID %>').value = price;
    }
</script>

Code behind

Session["Price"] = HiddenPrice.Value.ToString();

Reference: Accessing & Modifying Session from Client-Side using JQuery & AJAX in ASP.NET

Upvotes: 4

Related Questions