views:

48

answers:

2

Hi, I am trying to create a link, which will onclick change a session variable like this


<a href="/Index" onclick="<% HttpContext.Current.Session["location"] = location;%>" >
    <%=location%>
</a>

However, during processing the page the session changes on its own during generating each anchor element (with this onclick attribute). So I would like to create a javascript function like


<script type="text/javascript" >
    function session(location) {
        HttpContext.Current.Session["location"] = location;
    }
</script>

Unfortunatelly, I don't know enough, so this doesn't seem working.. Any ideas? Thanks in advance

+2  A: 

Session is an ASP.NET server object that is not accessible from the client through JavaScript directly (Session may be stored as a cookie on the client, but then even then, it is not designed to be accessed from the client-side directly). You could handle what you want to do in a number of ways -

  1. Store a value in a hidden input when a link is clicked and then read that value server-side and store in Session.

  2. Store in Session on postback in a Click event handler for the anchor. You may want to use the asp:HtmlAnchor control for this and set up an event handler for the OnServerClick event

Russ Cam
I am sorry, but could you please be more specific (maybe with a small example)? I am still quite new to web development and after another hour trying I am still where I was before. I am using the asp.net mvc framework, so I would be rather interested in the second option, since I don't want to create an extra action accepting HttpVerbs.Post for each action. Or maybe I am completely lost in here..
Trimack
I'm not overly familiar with how the ASP.NET MVC framework operates and my answer was based on ASP.NET webforms. I am more than happy for someone to edit the post to include an MVC example. In the meantime, i'll see if I can find a resource to update my answer with.
Russ Cam
+2  A: 

Carefully read through this thread: How is ASP.NET and Javascript related?.

deceze