开发者

How do I set a value to the Session in asp.net on an onClick event of a normal htmlElement?

开发者 https://www.devze.com 2022-12-23 10:02 出处:网络
I need to make a Function that receives a Session Key and a Session Value and call this function on a normal HTML onClick event. When this function is called the Session variable is assigned the Key I

I need to make a Function that receives a Session Key and a Session Value and call this function on a normal HTML onClick event. When this function is called the Session variable is assigned the Key I sent with the Value I sent. So far I have this:

<script runat="server" type="text/C#">
        protected void setSessionValue(string key, string value)
        {
            Session[key] = value;
        }  
</script>

But when I try to call if like so:

onclick="setSessionValue('itemID','3345');"

Its not working and giving me an开发者_如何学C error. Any help? I'm using c# and asp.net but I can't use code behind and need to work everything off the page.


You cannot set anything to the session from the client because session in stored on the server.


You are trying to invoke a server method from a client side javascript. You can either do as what Oded suggested or, you can use the ASP.NET Ajax to achieve the same.

The below link would be a good starting point on how to do this using ASP.NET Ajax.

ASP.NET Ajax Exposing Webservices to Ajax

Update 1:

Another useful link


You are trying to call the server side (C#, VB.NET) code from the client side (Javascript).

This is not possible.

You can change your HTML control to be server side, by adding the runat="server" attribute on it - you will also need to change the type to one that is recognized serverside, namely <asp:HtmlLink />.


Try using

OnServerClick="setSessionValue('itemID','3345');"

instead of

onclick="setSessionValue('itemID','3345');"


Ok I managed to find a solution on my own thanks to all of your submissions, listen to this. I added a javascript function as follows:

function setSessionValue(key, value) {
     $.post('setSession.aspx?key=' + key + '&value=' + value);
}

and added an aspx file with the following code within it:

<%@ Page Language="C#" %>
<% 
    Session[Request["key"]] = Request["value"]; 
%>

Basically this worked just fine, all I needed was a little jQuery. Thanks to all for your suggestions.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号