简体   繁体   中英

Set Session value using Javascript and retrieving the same using razor umbraco

I have written following code let say in Page 1

<a Onclick="setSessionValue()" href="page2"></a>

<script type="text/javascript">

        function setSessionValue()
        {
            var selectedCarNoideId = "1026";                                
            '<%Session["BannerNoideID"] = "'+ selectedCarNoideId +'";%>'                
            alert('<%=Session["BannerNoideID"]%>');         
        }

</script>

And now retrieving session value on other page (Scripting File .chtml) using following code.

<h2>Session-:@Session["BannerNoideID"]  </h2>;

In the Page 1 alert PopUp displays "1026" as session value

But In Page 2 tag display following value as a output of session .

"Session-:'+ selectedCarNoideId +'"

Am I missing any thing ?

You're mixing javascript and server-side code in such a way that the javascript isn't being evaluatd as you expect.

The Server side session variable is literally being set to '+ selectedCarNoideId +' as the page is being rendered. Javascript in this case is doing nothing to set the session value.

Although why you're getting the alert message to display 1026 is anyone's guess - is the BannerNoideID session variable being set elsewhere as well perhaps?

If you're trying to save a variable generated client-side with Javascript in the session on the server, you will need to submit it.

One way to do it would be to create a simple MVC Controller (WebAPI by default is sessionless) and then POST the value to it using Ajax or a form post.

Alternatively, you could pass the id through on the QueryString to the next page or something like that - that approach is probably the simplest.

Without knowing more about your setup, workflow and business logic I can't really suggest much more.

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