简体   繁体   中英

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

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 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 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 /> .

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM