Search code examples
c#asp.netinline-code

Dynamically assigning a class to a div tag


I have a div where I swap out the background image on load when a button is clicked. But it loads the image specified in the css first then loads the image I tell it to in the event. You can see this change of image as the page does a post back. Trying to reduce the "flicker" I decided to make 5 classes in my CSS and dynamically assign that class to the divs class tag. I made a class for each of the 5 image backgrounds. However it wont let me put inline code in the div. It doesn't like this line class="<%= strMenuButtonClass%>">

<%
  //see which menu button was clicked
  //--------------------------------------------------------------------
  int menuButtonId = Convert.ToInt32(Request.QueryString["buttonId"].ToString());
  string menuButtonClass = "divMasterCol1Button1";
  switch (menuButtonId){
  case 1:
      menuButtonClass = "divMasterCol1Button1";
      break;
  case 2:
      menuButtonClass = "divMasterCol1Button1";
      break;
  case 3:
      menuButtonClass = "divMasterCol1Button1";
      break;
  case 4:
      menuButtonClass = "divMasterCol1Button4";
      break;
  case 5:
      menuButtonClass = "divMasterCol1Button1";
      break;
  }
  //-----------------------------------------------------------------------
%>

And here is the div tag...

<div id="divMasterCol1" class="<%= strMenuButtonClass%>">
        --content goes here--
</div>

Solution

  • Two problems.

    First, strMenuButtonClass is not the correct name. Should be menuButtonClass.

    Secondly, menuButtonClass needs to be a public property or field in the C# code in order for the .aspx to see it.

    public string menuButtonClass {get; set;}