Avatar of Eric Christianson
Eric Christianson
Flag for United States of America asked on

I need to make my existing Javascript Menu conditional within my ASP.Net/C# Application

I have a large ASP.Net/C# application that uses a JavaScript menu.  The person who wrote the menu is long gone, and now I need users who log in to see different menu options on the pages.
I thought of two ways I can do this, and I cannot get either one to work because I do not understand JavaScript well enough.  I am using HTML 4.01.

First idea: add a few lines to the HTML HEAD section of pages to point to a different menu program based on a session variable I set in the Login page:
if (Session["UserType"].ToString() == 'external')
        <script language="JavaScript" src="MenuExternal.js" type="text/javascript"></script>
else
        <script language="JavaScript" src="MenuInternal.js" type="text/javascript"></script>

Second idea: add conditional if statements in the JavaScript program itself:
if (Session["UserType"].ToString() == 'external')
      startMenu('mUserMaintenance', true, 0, 18, 111, subM);
            addItem('&nbsp; External Users', 'MenuNav.aspx?From=Menu&To=EditUsers_External.aspx', '');
            addItem('&nbsp; My User Account', 'MenuNav.aspx?From=Menu&To=EditUsers_Me_Only.aspx', '');
else
      startMenu('mUserMaintenance', true, 0, 18, 111, subM);
            addItem('&nbsp; Internal Users', 'MenuNav.aspx?From=Menu&To=EditUsers.aspx', '');
            addItem('&nbsp; External Users', 'MenuNav.aspx?From=Menu&To=EditUsers_External.aspx', '');
            addItem('&nbsp; My User Account', 'MenuNav.aspx?From=Menu&To=EditUsers_Me_Only.aspx', '');

What I do not know how to do is mix C# (session variables) and JavaScript, or even if it's possible at all.  I have attached the JavaScript menu code.  The actual menu code that I modify regularly is about 2/3rds of the way down.

Thanks,
Eric Christianson
menu.js
* if statementsHTMLJavaScriptC#

Avatar of undefined
Last Comment
Julian Hansen

8/22/2022 - Mon
Julian Hansen

how to do is mix C# (session variables) and JavaScript
You can't directly. C# code "writes" the HTML that is sent to the browser. Once the HTML arrives in the browser the C# code (in most cases) has finished running.

What you can do is emit JavaScript code that includes JS variables that are set to values from the C# session for instance

(For illustration purposes only - adapt for your code)
<script>var __sessionID=<%= SessionID%>;</script>

Open in new window

Now when your page is ready there will be a global _sessionID variable that your JavaScript code will be able to access.

Option 1 won't really work - both scripts will be included. You would need to load the script dynamically using one of three methods

1. jQuery $.getScript
2. Document write (providing it is in the body of the document and does not run after document ready)
3. Dynamically creating a <script> element and appending it to the body

Neither of the strategies, in my view, is optimal but an alternative would require a radical change from your existing architecture which I don't believe is in your best interest right now. So working with what you have - if you have two distinct scenarios for menus based on a variable then these options are good enough.
Eric Christianson

ASKER
Hi Julian -

You're going to have to bear with me.  I understand that my option 1 won't work, so I will be changing the code in Menu.js.

Where would I insert the line (like) : <script>var __sessionID=<%= SessionID%>;</script>, and how, specifically, would I assign a value to that session variable?  You gave me three options, but I'm not familiar with how to apply what you suggest to my application.

Thanks,
Eric
Julian Hansen

Ok, you first need to understand that your C# application writes an HTML file. The file that appears in the browser was generated by your server script.

For that page to operate it needs to have in it all the data that makes the page work. To get that data there your C# script must write that data out as JavaScript statements.

Somewhere in your C# rendering code (I can't tell you where because I have not seen your code) you put an output statement - something like this
Response.write("<script>var _sessionID=" + Session.ID + ";</script>");

Open in new window

As long as the above comes before any JavaScript code that attempts to use the variable _sessionID (or the code that uses the var is inside a document ready function) the value _sessionID will be available globally throughout the script.

For instance you might have a JavaScript function

(The code below is only an illustration - it will not work with your code without modification)
window.addEventListener('load', function() {
   if (_sessionID == 1) {
     showAdminMenu();
   }
   else {
     showUserMenu();
   }
});

Open in new window

Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
Eric Christianson

ASKER
Hi Julian -

Based on my (poor) interpretation of your instructions, this is what I did, and the error that was thrown:

In my Login.aspx.cs (code behind) I inserted the following line of code:

 Response.Write("<script>var _sessionID=" + '1' + ";</script>");


In my HTML, I inserted the following code.  

<HTML>
  <HEAD>
            <title>Default</title>
            <!--<script language="JavaScript">window.history.forward();</script> -->
            <meta content="Microsoft Visual Studio 7.0" name="GENERATOR">
            <meta content="C#" name="CODE_LANGUAGE">
            <meta content="JavaScript" name="vs_defaultClientScript">
            <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">

       <script language="JavaScript" type="text/javascript">
            window.addEventListener('load', function () {
                if (_sessionID == '1') {
                    src = "menu_Internal.js";
                }
                else {
                    src = "menu_External.js";
                }
            });
            </script>
           

<LINK href="CSS/LabLinQ.css" rel="stylesheet">
  </HEAD>


Even though the code compiled, running the application threw the following error from my HTML:

JavaScript runtime error: Object doesn't support property or method 'addEventListener'

Am I on the right track?

Thanks,
Eric
Eric Christianson

ASKER
Hi Julian -

I looked up the error and changed the HTML code to use attachEvent instead.

       <script language="JavaScript" type="text/javascript">
            window.attachEvent('load', function () {
                if (_sessionID == '1') {
                    src = "menu.Internal.js";
                }
                else {
                    src = "menu_External.js";
                }
            });
            </script>

It compiles and runs, but now I don't get any menu.  (menu_Internal.js is still there.)
Julian Hansen

A few pointers
1. the attributes for <script> (src / language) have been deprecated - you can leave them out.
<script>
 // JavaScript here
</script>

2. You can try document.addEventListener - window is valid as shown in this sample
<script>
document.addEventListener('load', alert('Document Load through document.addEventListener()'));
window.addEventListener('load', alert('Document Load through window.addEventListener()'));
</script>

Open in new window

Working sample here

3. You don't seem to be on the right track with this code
if (_sessionID == '1') {
  src = "menu_Internal.js";
}
else {
  src = "menu_External.js";
}

Open in new window

It looks like you are trying to dynamically set the src of a JavaScript file to import - unless you are going to employ one of the techniques described in my earlier post (which you alluded to you were not going to try) to dynamically load a script.

4. I did not see the output of the var _sessionID anywhere in the code you posted - did you just leave it out?
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Eric Christianson

ASKER
Hi Julian -

I am confused.  Of course I'll try any suggestion you have.  What I alluded to before is that I don't understand how to implement what you are suggesting, based on the words you used.  I just don't have the expertise to interpret, for example,  'Dynamically creating a <script> element and appending it to the body'.  I don't know how to do that.  So I am using the code you are giving me and try to correct it for sue in my app.

I don't believe I am outputting the _sessionID variable?  I (thought) I was setting it in my Login codebehind file, and then my default page was supposed to pick it up and point to the correct javascript file (internal or external js files).

So in my Login code I say:  Response.Write("<script>var _sessionID=" + '1' + ";</script>");
(I am guess that this code put's the value of '1' into _sessionID, correct?)

In my default web page which is called by the Login page, I have the following code in the HEAD section:  (BTW - I get an error from HTML 4.01 if I leave out the language/type stuff - go figure)

        <script language="JavaScript" type="text/javascript">
            window.attachEvent('load', function () {
                if (_sessionID == '1') {
                    src = "menu.js";
                }
                else {
                    src = "menu.js";
                }
            });
            </script>
(My assumption here is that this code picks up _sessionID ("1") and decides which menu code to run (internal or external))

Thanks,
Eric
Julian Hansen

I looked up the error and changed the HTML code to use attachEvent instead.
Then you must be using IE8 as any real browser supports addEventListener. You might want to consider using the jQuery library or similar that will give you access to code that is cross platform.

According to Microsoft - attachevent is no longer supported (https://msdn.microsoft.com/en-us/library/ms536343(v=vs.85).aspx) so I would consider finding an alternative.

It compiles and runs, but now I don't get any menu.  (menu_Internal.js is still there.)
You won't because
src = "menu_Internal.js";

Open in new window

Does nothing but assign a string to the variable src - JavaScript does not know what to do with src - it has no bearing on the loading of scripts. As discussed in earlier posts your Option 1 is not going to work unless you use one of the 3 dynamic script loading techniques I mentioned earlier.

Your best bet is using the variable to run different functions in your JavaScript file that render the different menus.
Eric Christianson

ASKER
Please disregard the  src = "menu.js"; code - I cut and pasted the wrong iteration of what I am working on.  This code actually says

                if (_sessionID == '1') {
                    src = "menuInternal.js";
                }
                else {
                    src = "menuExternal.js";
                }
Your help has saved me hundreds of hours of internet surfing.
fblack61
Julian Hansen

Our posts are out of synch - so ignore my last for now
'Dynamically creating a <script> element and appending it to the body'.
I did not provide references because you agreed you were going with option 2

So in my Login code I say:  Response.Write("<script>var _sessionID=" + '1' + ";</script>");
(I am guess that this code put's the value of '1' into _sessionID, correct?)
Yes - but you need to change 1 to whatever value you are going to use in your script AND the result of the above must be to write the <script> ...</script> to your HTML - if it is not doing that there is no way the JavaScript on the page will pick it up.

Again to try and explain this - you need to write C# code that outputs JavaScript with the data expressly printed out as you need it - your code has to write the following to the HTML that ends up in the browser
<script>var _sessionID='external';</script>

Open in new window

Or (depending on the state of sessionID - again change to suite your app requirements)
<script>var _sessionID='internal';</script>

Open in new window

When you do a view source in the browser you must see the above line somewhere in the code - if you are not - then your output (Response.write) is not firing or not firing correctly.


(My assumption here is that this code picks up _sessionID ("1") and decides which menu code to run (internal or external))
Yes - you are writing JavaScript into your output that contains state information from your server code so that the JavaScript code on the page can access it.
Think of it like this - you are sitting side by side with the C# application when the request comes in - instead of the C# code outputting HTML you manually type it in. You look at the sessionID value - if it is a value that indicates internal then you type the following into the output file
<script>var _sessionID='internal';</script>

Open in new window

However if the state indicates external you write the following to the output file
<script>var _sessionID='external';</script>

Open in new window

That is done so now you type into the file the following
<script language="JavaScript" type="text/javascript">
            window.attachEvent('load', function () {
                if (_sessionID == '1') {
                    src = "menu.js";
                }
                else {
                    src = "menu.js";
                }
            });
            </script>

Open in new window

Now you are done creating the file so you save it and send it to the browser. You have put all the data into the file that the page needs in order to render correctly. Now just take yourself out of the picture and give the task you have just performed (creating the file) to the C# code - it is the same thing.
Julian Hansen

Please disregard the  src = "menu.js"; code - I cut and pasted the wrong iteration of what I am working on.  This code actually says
The string is irrelevant - the method is wrong.
Eric Christianson

ASKER
Hi Julian -

So we're back to square one.  How do I use the variable (_sessionID) to run different functions in (my) JavaScript file that renders the different menus?  Can you provide me with an example of code that will do that?  

I am running IE because that is what this system was written for in in 2004, and is certainly the cause of many of the issues we are having in 2017.  But I don't get to make the rules, unfortunately.

Thanks,
Eric
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Julian Hansen

So we're back to square one.
How so - I have given you the process you need to follow

1. In your C# code implement a statement to write out a line of JavaScript that includes the session state you want to act on.
2. In your code put your two different menu renderers into two different functions
3. In your code run a JavaScript function that uses the variable from 1 to decide which of the two renderers to use.

Let me know which part is still not clear.
Julian Hansen

Example (I cannot give you an exact example because I don't have a .Net setup to demonstrate it)

This shows the resulting file
<!-- THIS LINE IS OUTPUT FROM YOUR C# CODE AND CHANGES 'internal' / 'external'
       DEPENDING ON THE STATE OF THE SERVER sessionID -->
<script>var _sessionID='internal';</script>

<!-- THIS CODE IS STATIC IT CAN JUST BE INCLUDED -->
<script>
function RenderInternalMenu()
{
    console.log('Output internal menu from here');
}
function RenderExternalMenu()
{
    console.log('Output external menu from here');
}
if (document.addEventListener) {
   document.addEventListener('load', onDocLoad());
}
else {
   document.attachEvent('load', onDocLoad());
}
function onDocLoad()
{
   if (_sessionID == 'internal') {
      RenderInternalMenu();
   }
   else {
     RenderExternalMenu();
   }
}
</script>

Open in new window

Julian Hansen

Here are more options - if you want to dynamically include the script (rather than calling functions)

Method 1: dynamically load based on _sessionID variable
function onDocLoad()
{
   if (_sessionID == 'internal') {
      src = 'menu.Internal.js';
   }
   else {
      src = 'menu.External.js';
   }
   
   var sc = document.createElement('script');
   sc.src = src;
   document.getElementsByTagName("head")[0].appendChild(sc);
}

Open in new window

Another option is instead of writing out the var _sessionID you instead do this (preferably in the <head> section of your target document)

if (sessionID == 'internal) {
    Response.write("<script src=\"menu.Internal.js\"></script>");
}
else {
    Response.write("<script src=\"menu.External.js\"></script>");
}

Open in new window

Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
Eric Christianson

ASKER
HI Julian -

I've tried everything you've given me, as well as a dozen variations of same, and still no joy.  But I feel we're almost there.  When I can get the  code to compile I don't get either menu but also no errors.  I'm going to have to pick this up again in the morning.

This is the latest content in my C# code-behind in the Login page.  

if (Session["UserType"].ToString() == "INTERNAL")
{
    Response.Write("<script src=\"menu_Internal.js\"></script>");
}
else
{
    Response.Write("<script src=\"menu_External.js\"></script>");
}                

Tomorrow I will start again on the code imbedded in the HTML on pages that I wish to show a different menu.

Thanks,
Eric
Julian Hansen

Two questions
1. Where in your code is this happening
if (Session["UserType"].ToString() == "INTERNAL")
{
    Response.Write("<script src=\"menu_Internal.js\"></script>");
}
else
{
    Response.Write("<script src=\"menu_External.js\"></script>");
}                

Open in new window

Context is important - simply writing out the above is no good unless it is done in the right place

2. Can you do a view source on your page and post the results here so we can see what is being rendered out.
Eric Christianson

ASKER
Good Morning Julian -

1.  I'm getting new errors this morning, so I started over again.  The following code is in my Login page (login.aspx.cs), in the C# code-behind for the Login button.  A dozen lines below this is the code that navigates the user to the Default page (default.aspx).

if (Session["UserType"].ToString() == "INTERNAL")
{
    Response.Write("<script>var _sessionID=" + "internal" + ";</script>");
}
else
{
    Response.Write("<script>var _sessionID=" + "external" + ";</script>");
}


2. After entering my password and clicking on the login button, I receive two errors ('Internal' is undefined), and ('Unterminated string constant') and then the Default.aspx page displays.  If I view the source, this is what I get:

<script>var _sessionID=internal;</script>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
  <HEAD>
            <title>Default</title>
            <!--<script language="JavaScript">window.history.forward();</script> -->
            <meta content="Microsoft Visual Studio 7.0" name="GENERATOR">
            <meta content="C#" name="CODE_LANGUAGE">
            <meta content="JavaScript" name="vs_defaultClientScript">
            <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
            <LINK href="CSS/LabLinQ.css" rel="stylesheet">

       
        <script language="JavaScript" type="text/javascript">
            if (sessionID == 'internal') {
                Response.Write("<script src=\"menu_Internal.js\"></script>");
            }
            else {
                Response.Write("<script src=\"menu_External.js\"></script>");
            }
        </script>

  </HEAD>
      <body>
            <html>
      <head>
            <meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
      </head>
      <body bgcolor="#ffffff" leftmargin="0" marginwidth="0" topmargin="0" marginheight="0">
            <table border="0" cellpadding="0" cellspacing="0" width="100%" background="Includes/Header2.gif">
                  <tr>
                        <td width="100" style="height: 58px"><img src="Includes/Header.gif" width="203" height="58" border="0"></td>
                        <td width="100%" background="Includes/Header2.gif" style="height: 58px"></td>
                  </tr>
            </table>
      </body>
</html>
<form method="post" action="Default.aspx" id="Default">
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTU4NjAxNDQ3M2Rk8bIOk2Pix286/fukGNuaB6vWIZiUtBseWhSxt+xl1bs=" />
</div>

<div class="aspNetHidden">

      <input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="8C91BCF5" />
</div>
                  <TABLE id="Table1" cellSpacing="1" cellPadding="1" width="918" border="0" align="center" style="WIDTH: 918px; HEIGHT: 555px">
                        <TR>
                              <TD>
<img id="Image1" src="Bitmaps\LabLinQWeb.gif" style="height:551px;width:960px;" /></TD>
                        </TR>
                  </TABLE>
            </form>
            

<html>

      <head>
            <meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
            <LINK href="/LMOL\CSS\LINQware.css" rel="stylesheet">
      </head>

      <body bgcolor="#ffffff" leftmargin="0" topmargin="0">
            <table border="0" cellpadding="0" cellspacing="0" width="100%" height="100%">
                  <tr height="10" valign="top">
                        <td bgcolor="white" valign="top" width="100" background="/LMOL\Includes/Footer2.gif" style="height: 10px"><a href="http://www.precisionmetrology.com" target="_blank"><img src="/LMOL\Includes/Footer.gif" border="0"></a></td>
                        <td nowrap bgcolor="white" valign="middle" background="/LMOL\Includes/Footer2.gif" style="height: 10px" >
                              <p class="TextLabel" style="font-size: xx-small" align="right">&nbsp;&nbsp;&nbsp;Precision Metrology, Inc., 7350 N. Teutonia Avenue, Milwaukee, Wisconsin 53209&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="http://www.PrecisionMetrology.com"><span
                        style="color: blue; font-size: xx-small;">www.<span style="color: #0000ff">PrecisionMetrology</span>.com</span></a>
                        &nbsp; &nbsp; &nbsp;
                    </p>
                        </td>
                  </tr>
                  <tr height="14" valign="top">
                        <td bgcolor="white" width="100" height="14"></td>
                        <td bgcolor="white" height="14" >
                              <p class="copyright"></p>
                        </td>
                  </tr>
                  <tr height="100%" valign="top">
                        <td width="100" height="100%" bgcolor="white" valign="top" align="left"></td>
                        <td height="100%" bgcolor="white" valign="top" align="left"></td>
                  </tr>
            </table>
      </body>

</html>
      </body>
</HTML>







Thanks,
Eric
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Julian Hansen

Take a look at this code

<script language="JavaScript" type="text/javascript">
            if (sessionID == 'internal') {
                Response.Write("<script src=\"menu_Internal.js\"></script>");
            }
            else {
                Response.Write("<script src=\"menu_External.js\"></script>");
            }
        </script>

Open in new window


This is wrong - that should have executed as C# code to produce one of the following lines
<script src="menu_Internal.js"></script>

Open in new window

OR
<script src="menu_External.js"></script>

Open in new window

So instead of seeing the first block of code we should be seeing one of the above to lines.

That tells me - however you have implemented this - is not as C# code but in a way that it outputs the C# code instead of executing it.
Eric Christianson

ASKER
Hi Julian - I am only trying to implement what you are telling me to do.  Telling me I have it wrong does not help.  I know I have it wrong, because it isn't working.

I am a FoxPro programmer.  Yes, FoxPro.  Half the software running in this company is still running FoxPro, so about ten years ago they hired me (an old FoxPro programmer - I'm 60 now) to manage and improve on their software for them 'until it breaks'.  Amazingly, it's now 2017, and it hasn't broken.  There are millions of records, over hundreds of files, under dozens of apps.  
The other half of their software is written in Asp.Net, C# and SQL, and the guys who wrote it are long gone.  The company figures that I'm a 'programmer' so they have me managing that as well, although I mainly stick to small modifications.  Considering my background, it's amazing I've been able to accomplish what I have.  I joined Experts Exchange about 10 years ago so that when I do run up against an issue in Asp.Net, C# or SQL, I have someone to turn to for help.

Now, when you say things like ...

1. jQuery $.getScript
 2. Document write (providing it is in the body of the document and does not run after document ready)
 3. Dynamically creating a <script> element and appending it to the body

It's like pearls before swine for me, as I have told you repeatedly.  I have no clue what that means.  Not any of it.

I feel that this coding issue is not that big of a deal, but I could certainly be wrong.  I need to tell HTML that it needs to conditionally run JavaScript menus based on a variable I set in C#.  That means most likely two pieces of code - one in the C# code behind, and one imbedded in the HTML.  
The JavaScript menus exist and work, the place in the C# code-behind is all set up, already knowing who logging in is external and who is internal.  The two hundred + web pages of the .Net application exist and work perfectly.  But the user can only see and work with a single menu, and I need them to work with two, conditionally.  In my mind, all the hard work is done.  This shouldn't be this difficult.

Over the years I have become very good at tweaking code I am not familiar with to make it work.  What I am definitely NOT good at is interpreting someone's instructions on how to write the code.  It's not a language I know.  I have tried my best to take your code, and interpret your instructions, to get this working, and I have failed (so far).

Julian, if you can't help me, perhaps there is someone else there that can.  I just need to get it done.  No hard feelings.

With respect,
Eric
Julian Hansen

Eric, I must apologise if I have in any way offended you - that was not my intention.  I am doing my best to help you but you are my eyes and my hands - I can only guide you as I don't have your code base here so I cannot give you a complete solution. Also remember that you have had ample time with your code to understand the ins and outs - I have had a few minutes while working on other projects and other questions - I have (or had) no knowledge of your skill level or experience. A large part of answering questions on EE is finding out what the actual question is - we rely on feedback from the askers to take the question forward.

Having said that lets get back to solving your problem. I have learned more about what you are doing and looking back at your original question there was some ambiguity over suggestion 1. I interpreted Suggestion 1 as JavaScript code - which won't work - however it will work as C# code.

The other red herring was the bit about passing a variable to JavaScript - in this case that is not actually necessary but it did distract us for a bit.

If I can summarise the problem - you have two menu systems each of which is run from different JavaScript files. You need to include ONE of these files based on the state of a session variable on the server.

This is actually a trivial task of running the condition statement on the server and then simply emitting the correct <script> reference for the menu you want to use. I am not a .Net developer so I was attempting to solve this by giving you the direction and letting you do the coding. However, in the interests of resolving this question I spun up VS2012 and put together a small application to demonstrate the concept.

Here is my code behind - simple class that contains the SessionID which is randomly assigned a value of 1 or 2
using System;

namespace t2286
{
    public partial class _Default : System.Web.UI.Page
    {
        public int SessionId;
        protected void Page_Load(object sender, EventArgs e)
        {
            Random rnd = new Random();
            SessionId = rnd.Next(1, 3);
        }
    }
}

Open in new window

The ASPX page
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="t2286._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<%
if (SessionId == 1)
    Response.Write("<script src=\"http://code.jquery.com/jquery.js\"></script>");
else
    Response.Write("<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.j\"></script>");
%>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <%=SessionId %>
    </div>
    </form>
</body>
</html>

Open in new window

You can see it working here

Again, please accept my apologies for the less than exemplary service - it is not how we operate here on EE.
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
Eric Christianson

ASKER
Hi Julian -

No apology necessary - I am not a proud man, and this is just code.  No worries.  As ridiculously complex as my work is, I wouldn't want to do what you do for a living.

I have been back on this now for a couple of hours, and the following HTML is the only thing that I've been able to get to compile.  If I leave the (<% and %>) characters around the code like you have it, it blows up with 'variable MenuId not found', and other errors).

The correct variable is being set in C#, and when the following HTML runs, errors are thrown in the correct JavaScript menu file (menu.js and menu_External.js).  So this is almost working.  

My gut says that what I have below (in bold) however is wrong - I just can't write it that way (even though it compiles and passes me through to the correct menu file)  I feel the plain text in the HTML will cause a problem once the Default.aspx page renders - but I haven't been able to get that far yet.

I am hoping that you can look at the bold part below, and suggest an obvious syntax fix for it.  While the correct menu file is being executed, the errors look to me like something coming in is not right, which beings me back to the odd-looking HTML.

<%@ Reference Control="~/ucSecure.ascx" %>
<%@ Register TagPrefix="uc1" TagName="ucSecure" Src="ucSecure.ascx" %>
<%@ Page language="c#" Inherits="LMOL._Default" CodeFile="Default.aspx.cs" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
    <HEAD runat="server">
            <title>Default</title>
            <!--<script language="JavaScript">window.history.forward();</script> -->
            <meta content="Microsoft Visual Studio 7.0" name="GENERATOR">
            <meta content="C#" name="CODE_LANGUAGE">
            <meta content="JavaScript" name="vs_defaultClientScript">
            <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
            <LINK href="CSS/LabLinQ.css" rel="stylesheet">

            if (MenuId == "INTERNAL")
            Response.Write("<script src=menu.js type="text/javascript"></script>;
        else
            Response.Write("<script src=menu_External.js type="text/javascript"></script>;
       

  </HEAD>
(body stuff is here)
</HTML>
Julian Hansen

This needs to be inside <% %> script tags
 if (MenuId == "INTERNAL")
            Response.Write("<script src=menu.js type="text/javascript"></script>;
        else
            Response.Write("<script src=menu_External.js type="text/javascript"></script>;

Open in new window


If MenuId is not available - are you sure you have made it public in your code behind?
Eric Christianson

ASKER
Hi Julian -

Yes, the variable is public (see code below).  And, execution throws an error in the correct JavaScript file.  So we know the HTML is pointing to the right file.  (Look at the bottom of this post for a second approach.)

namespace LMOL
{
      public partial class Login : System.Web.UI.Page
      {
            #region Declarations
                     public string MenuId;
            #endregion Declarations
      
            #region Page_Load
            protected void Page_Load(object sender, System.EventArgs e)
            {
                  Session["CallingPage"] = "Login.aspx";   /// Identifies this page for Return transfers
                  if(!IsPostBack)
                  {
                        div_Help.Visible = false;


From the code behind the Login button:

protected void cmdLogIn_Click(object sender, System.EventArgs e)
{
      switch (txtLoginID.Text)
      {
            case "mm44":
                  {
                             MenuId = "INTERNAL";
                             Server.Transfer("Default.aspx");

_____________________________________

From the beginning we have been trying to point the execution at one or the other of two JavaScript menu programs (menu.js and menu_External.js.  Remember way back when, I said there were two approaches I could think of?  If we can't get Option 1 to work, how about Option 2?

Is there any way to get a variable set in C# from the Login page into the menu.js menu program?  

This is the idea...

"If the user is 'INTERNAL'"

    var pMenu = new PopupMenu('pMenu');
    with (pMenu)
    {

        startMenu('root', false, 0, 40, 18, hBar);
              addItem('&nbsp; Home', 'Default.aspx', '', hBar, 50);
              addItem('&nbsp; Receiving', 'mReceiving', 'sm:', hBar, 70);
              addItem('&nbsp; Services', 'mServices', 'sm:', hBar, 65);
              addItem('&nbsp; Shipping', 'MenuNav.aspx?From=Menu&To=Shipping.aspx', '', hBar, 65);
              addItem('&nbsp; Billing', 'MenuNav.aspx?From=Menu&To=Billing.aspx', '', hBar, 65);
              addItem('&nbsp; Estimates', 'mEstimates', 'sm:', hBar, 70);

              .
              .
              .
    }

else

    var pMenu = new PopupMenu('pMenu');
    with (pMenu)
    {

        startMenu('root', false, 0, 40, 18, hBar);
              addItem('&nbsp; Home', 'Default.aspx', '', hBar, 50);
              addItem('&nbsp; Services', 'mServices', 'sm:', hBar, 65);
              .
              .
              .
    }

endif
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Julian Hansen

Is there any way to get a variable set in C# from the Login page into the menu.js menu program?  
Yes but it involves getting hold of MenuID which you are having trouble with. If you can access it to output it to the script then you can access it to do the logic test.

Something is not right here though - the sample I setup was exactly what needs to be done in its simplest form and it works - something else must be preventing this from working.
Eric Christianson

ASKER
Hi Julian -

I went back and changed the variable to an integer, and copied your exact code that points to two web pages.  (see attachment) The second image is the error that will be thrown upon execution.  You can see that MSVS has already flagged it as bad.  I believe you - it should work from what little I know about HTML and JavaScript, but I can't see any syntax problem.

Doc1.docx
Julian Hansen

Ok but you are using it in a file that has CodeFile="Default.aspx.cs" and it appears to be defined in a file called Login.aspx.cs
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
Eric Christianson

ASKER
Good Morning Julian -
Yes, each of the 100+ web pages in the system has a line in it that defines the menu:  
       
<script language="JavaScript" src="Menu.js"></script>


We have been trying to change that line to point to two menu files, conditionally, instead of one, based on a variable set in C#, from the Login page.

Thanks,
Eric
Julian Hansen

Ok, well that was quite an important point.

The question is - one each page where do you get the Session information from. I am assuming it is globally available in some construct?
Eric Christianson

ASKER
Hi Julian -

Right now, there is no global session variable.  Right now, every page points to the same menu.  I am trying to change that.  
I want to pass in a variable so that each page can point to one of two menus.  (Now), that variable is being set in the Login page.  I want that variable visible in all the other pages so they can run a specific menu, based on the variable.  That's what I thought we were trying to do here?
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
ASKER CERTIFIED SOLUTION
Julian Hansen

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Julian Hansen

@Eric,

Thanks for the points - I am interested to know if the above sorted out the problem and if you are now able to interchange the menus correctly?