简体   繁体   中英

How to call Javascript from C# PageLoad?

I want to ask How to call javascript from C# page load. My Javascript is

function Hide(lst) {
        if (document.getElementById) {
            var tabList = document.getElementById(lst).style;
            tabList.display = "none";

            return false;
        } else {
            return true;
        }
    }

and want to call from pageload

if (dtSuperUser(sLogonID).Rows.Count < 1)
        {

            //Call Javascript with parameter name tablist
        }

thanks

Actually, you can use pageOnload event to do so. Like this.

 protected void Page_Load(object sender, EventArgs e)
        {           
            if (IsPostBack)
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "show", "<script>document.getElementById('Your element').style.display = 'block'</script>");
            }
            else
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "show", "<script>document.getElementById('Your element').style.display = 'hidden'</script>");
            }
        }
String csName = "myScript";
Type csType = this.GetType();

// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;

// Check to see if the client script is already registered.
if (!cs.IsClientScriptBlockRegistered(csType, csName))
{
  cs.RegisterClientScriptBlock(csType, csName, 
      string.Format("Hide({0})", lst.ClientID));
}
RegisterStartupScript("Hide", string.Format(@"if (document.getElementById) {
        var tabList = document.getElementById('{0}').style;
        tabList.display = 'none';
        return false;
    } else {
        return true;
    }",lst));

Or if you already have the Javascript function rendered in the Markup

RegisterStartupScript("Hide",string.Format("Hide('{0}');",lst));

Are you using webforms or MVC? If using webforms check:

http://msdn.microsoft.com/en-us/library/Aa479011

Page.RegisterStartupScript("MyScript",
   "<script language=javascript>" +
   "function AlertHello() { alert('Hello ASP.NET'); }</script>");

Button1.Attributes["onclick"] = "AlertHello()";
Button2.Attributes["onclick"] = "AlertHello()";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM