c# - Call a Javascript function from aspx - Stack Overflow

Code from aspx.cs:.......button.OnClientClick = "onButtonClick(this)";.....Function in Java

Code from aspx.cs:

.......
button.OnClientClick = "onButtonClick(this)";
.....

Function in Javascript(written in the aspx file):

<script> 
        function onButtonClick(event) {
           ....
        }
</script>

The "program" didn't even get to the script.

Code from aspx.cs:

.......
button.OnClientClick = "onButtonClick(this)";
.....

Function in Javascript(written in the aspx file):

<script> 
        function onButtonClick(event) {
           ....
        }
</script>

The "program" didn't even get to the script.

Share Improve this question asked Nov 25, 2016 at 16:20 OmerOmer 962 gold badges3 silver badges10 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 1

Where are you calling your button.OnClientClick assignment? If it is in the page load or a button click event, it should work. If you are calling it in an ajax method, the button may be be rendered after the assignment, so maybe that's your problem.

protected void Page_Load(object sender, EventArgs e)
{
    Button1.OnClientClick = "clicky(this)";
}

On .aspx page, just before the closing tag:

<script>
   function clicky(e) {
      alert("click");
   }
</script>

You should be able to see onclick="clicky(this)"; when you inspect the element in the Chrome developer tools when you run the page.

Well its redundant to call a JavaScript with a asp button when you can always just use the on click method with a normal html button.

 <button onclick="onButtonClick()">Click me</button> 

However here is how you can do it with the following ways

Response.write("<script type=""text/javascript"">onButtonClick();</script>")

// OR
ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:onButtonClick(); ", true);
// OR 
string name = "onButtonClick()";
        ScriptManager.RegisterClientScriptBlock(this, typeof(string), "Key", name, true);
// OR    
ScriptManager.RegisterStartupScript(this, GetType(), name, false); 

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745001045a4605494.html

相关推荐

  • c# - Call a Javascript function from aspx - Stack Overflow

    Code from aspx.cs:.......button.OnClientClick = "onButtonClick(this)";.....Function in Java

    1天前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信