0

I have an IF/ELSE condition in my C# code (using webforms) and I want to use ClientScript.RegisterClientScriptBlock to change an anchor tag class

email = Business.Core.Profiles.Email.SetEmailAlertProfile(base.companyId, type);

// Email obj == null means no alert data for advertiser with this ID.
if (email == null)
    {
        EmailAction = "add";
        lblEmailText.Text = "Add to Email Alerts";
        //Change Anchor class to show remove image
        //ClientScript.RegisterClientScriptBlock(typeof(string), "ChangeAnchorClass", "<script>$('.jsPopUp btnAddEList active').addClass('jsPopUp btnRemoveEList active');</script>");
    }
else
    {
        EmailAction = "delete";
        lblEmailText.Text = "Remove from Emails";
        //Change Anchor class to show remove image
        ClientScript.RegisterClientScriptBlock(typeof(string), "ChangeAnchorClass", "<script>document.getElementById('hrefEmail').className = 'MyClass';</script>");

    }

My ELSE condition gives me the following error:

Microsoft JScript runtime error: Unable to set value of the property 'className': object is null or undefined

I have used client script in my project elsewhere but it is not working here.

Additional information:

This code is in a method which is called on page load. Don't know if that makes a difference.

nick gowdy
  • 6,191
  • 25
  • 88
  • 157
  • It's either running before DOM ready so it can't find the element, or it's running on a page that doesn't have an element with an `id` of `hrefEmail` at all. – Anthony Grist Mar 08 '13 at 15:04
  • @AnthonyGrist Ok if that's the case, which event on asp.net web forms life cycle do I fire this code? – nick gowdy Mar 08 '13 at 15:06
  • 1
    I'm not an ASP.net developer, so my knowledge is mainly limited to the client-side workings of the JavaScript code, but [this question](http://stackoverflow.com/questions/666519/difference-between-registerstartupscript-and-registerclientscriptblock) should cover what you need. Looks like you need to use `RegisterStartupScript` rather than `RegisterClientScriptBlock`. – Anthony Grist Mar 08 '13 at 15:08

1 Answers1

0

I changed this:

else
    {
        EmailAction = "delete";
        lblEmailText.Text = "Remove from Emails";
        //Change Anchor class to show remove image
        ClientScript.RegisterClientScriptBlock(typeof(string), "ChangeAnchorClass", "<script>document.getElementById('hrefEmail').className = 'MyClass';</script>");

    }

To this:

else
    {
        EmailAction = "delete";
        lblEmailText.Text = "Remove from Emails";
        //Change Anchor class to show remove image
        ClientScript.RegisterStartupScript(typeof(string), "ChangeAnchorClass", "<script>document.getElementById('hrefEmail').className = 'MyClass';</script>");

    }
nick gowdy
  • 6,191
  • 25
  • 88
  • 157