How to call Javascript from C# PageLoad?
I wan开发者_JS百科t 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()";
精彩评论