1

In a WebForms project, on a particular page, I have a javascript method in the aspx file. Inside I use 2 embedded code blocks.

<script type="text/javascript">
    function showMessage(idActityGroup) {
        var r = confirm("Message");
        if (r == true) {
            //First Code Block
            <%string idActityGroup = "' + idActityGroup + '";
            //Second Code Block
            '<%Session["waitList"] = "yes"; %>';
            //Last javascript instruction
            window.location.href = '/Register';
        }
</script>

The problem is that these two lines are executed each time a click event of a button is triggered. When in the event of the codebehind button it has done its work, it enters the aspx and executes those two lines. And I just want them to run when the function is called. The method is inside an updatePanel. I have tried to get the javascript function out of the updatePanel but the same thing is still happening.

Is there any way to avoid this behavior? Thank you very much.

1 Answers1

1

Before fixing your issue, you should understand clearly what is happening and why those two lines are executed every time you press a button. You should first review this document about the page lifecycle in ASP.net

Just after the prerender stage, the inline code (the 2 lines you are talking about) get executed and the HTML is then generated.

When you click a button, it submits a postback and ASP.net re-render the page, hence your 2 lines get executed a second time.

Now, I don't think you can achieve what you want this way. I.e. your second code block:

<%Session["waitList"] = "yes"; %>

would assigns "yes" to the 'waitList' key in the session state every time the page loads. You should instead try to generate a postback to handle this on the code behind.

<script type="text/javascript">
    function showMessage(idActityGroup) {
        var r = confirm("Message");
        if (r == true) {
            //First Code Block
            __doPostBack('handleMessageConfirmed',null)
        }
</script>
TSpark
  • 189
  • 1
  • 14
  • Thank you very much. As you have mentioned, it is not possible to prevent Embedded Code Blocks from execution, since with each call to the server the view is prerendered. The __doPostBack function helped me to solve the problem. – Rafael Cervera Aug 02 '17 at 08:04