Adding CSS with ListItem.Attributes.Add does not work

266 Views Asked by At

I have a function like this inside an ajax ModalPopupExtender:

private void BindListBox()
{
  var obj;
  // some code to bind obj 
  ListItem x = new ListItem(obj);
  x.Attributes.Add("class", "headerStyle");
  lstListBox1.Items.Add(x);
}

I put this function inside OnPreRender event with a code to initialize bootstrap datepicker. Due to some reason, I have to initialize datepicker inside OnPreRender

protected override void OnPreRender(EventArgs e)
{
   base.OnPreRender(e);

   String script = "$(document).ready(function() {$('#" + txtDate.ClientID + "').datepicker({format: 'dd-mm-yyyy',autoclose: true});});";
   ScriptManager.RegisterStartupScript(base.Page, base.Page.GetType(), String.Format("jQuery_{0}", txtDate.ClientID), script, true);        

   BindListBox();
}

Upon executing the code, the listbox item markup is not generated with the headerStyle class attributes. It has text and value but no class attributes.

I read about the attributes would be lost upon postback, but I don't think I have any postback after adding the class attribute. My Page_Load in ModalPopupExtender is empty, and my Page_Load in the ASPX that call the pop up has this code only:

protected void Page_Load(object sender, EventArgs e)
    {
        Page.Header.DataBind();
        if (!IsPostBack)
        {                
            ModalPopupExtenderForm.Show();
        }
    }

I'm not sure where is the problem.

I tried calling the function in the ASPX Page_Load or the modal pop up Page_Load but no changes.

Please advice.

1

There are 1 best solutions below

0
On BEST ANSWER

As a result, I'm unable to locate the root cause. It seems like some part of the ASPX life cycle mess up with my CSS and I have no idea which part is messing up. I have to do a tedious workaround on this.

1) Every time the listbox is binding to its data source, if the looping item is a header, I will push it into a string array.

2) When the looping into the listbox is completed, save the string array into ViewState

3) Create a function that will be called at the end of Page_Load

4) The function will retrieve every header in the string array ViewState and do the Attributes.Add()

I wouldn't consider this as a wise solution but at least it work for me.