开发者

Call a jQuery function from aspx.cs

开发者 https://www.devze.com 2023-03-23 05:37 出处:网络
I have a jQuery function to show a validation message in an asp.net login page. I put the script in a separate file named login.js (I\'ve called the js file from the html)

I have a jQuery function to show a validation message in an asp.net login page. I put the script in a separate file named login.js (I've called the js file from the html) The name of the function is loginMessage();

I need to know how to call it from aspx.cs in a button click event. I've tried to call the function directly in a button click eve开发者_StackOverflownt, eg :

protected void btnLogin_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{ 
  ...........
  The login validation process goes here
  ...........

  if (ds.Tables.Count == 0)
  { 
       loginMessage();
  } 
}

but I got this following error message when i tried to debug the page :

The name 'loginMessage' does not exist in the class or namespace 'School.Login'

Kindly help me about this query. Regards, Andha


This should do the trick:

btnLogin.Attributes.Add("onclick", "return loginMessage();");

Other examples here: http://www.devcurry.com/2009/01/execute-javascript-function-from-aspnet.html


You can't call a JS function within the code behind of an aspx page.

Instead use OnClientClick attribute of the btnLogin in the aspx/ascx page to trigger a JS function.

something like ..

<asp:Button id="btnLogin" runat="server" OnClientClick="return loginMessage()" .../>

EDIT: Updating the answer based on OP's edit to the question.

To call the js method on page load try this:

protected void btnLogin_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{ 
  ...........
  The login validation process goes here
  ...........

  if (ds.Tables.Count == 0)
  { 
    if (!IsClientScriptBlockRegistered("loginMessage"))
    {
        String loginMessage= "<script type=\"text/javascript\">loginMessage();</script>";
        RegisterStartupScript("loginMessage", loginMessage);
    }
  } 
}


The first result after a seach on Google with keywords "asp.net button client" points to this site http://msdn.microsoft.com/en-us/library/7ytf5t7k.aspx#Y570 It will be helpful for you.


You can use ScriptManager and ClientScriptManager for that.

An example:

protected void btnLogin_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{ 
  ...........
  The login validation process goes here
  ...........

  if (ds.Tables.Count == 0)
  { 
       Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "ValdationMessage", "loginMessage();", true);
  } 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消