简体   繁体   English

如何通过 jquery 或 java 脚本触发 asp.net 按钮事件?

[英]How can I fire an asp.net button event via jquery or java script?

I want when I click on "Doit" string it fire my asp.net button.我想当我点击“Doit”字符串时,它会触发我的 asp.net 按钮。

This is my "DoIt"这是我的“DoIt”

<a id="" href="#"">Doit</a>

And my asp.net button event is:而我的 asp.net 按钮事件是:

protected void Button1_Click(object sender, EventArgs e)
{
    Response.Redirect("rightclick.aspx");
}

How can I do this?我怎样才能做到这一点? Please help me..请帮我..

If Button1 already exists, have such code:如果Button1已经存在,有这样的代码:

<a id="myLink" href="#" onclick="document.getElementById('<%=Button1.ClientID%>').click(); return false;">Doit</a>

This will "auto click" the button thus trigger any server side code handling its click.这将“自动单击”按钮,从而触发处理其单击的任何服务器端代码。

Try:尝试:

<asp:LinkButton ID="MyLink" runat="server" onclick="Button1_Click">Doit</asp:LinkButton>

use the LinkButton ASP control to fire that event使用 LinkButton ASP 控件触发该事件

<asp:LinkButton id="something" onClick="Button1_Click" Text="DoIt" runat="server" />

To call a server side method on a client side event you need to do the following:要在客户端事件上调用服务器端方法,您需要执行以下操作:

1- Create the server side method: 1-创建服务器端方法:

void DoSomething(...) { ... }

2- Implement the System.Web.UI.IPostBackEventHandler.RaisePostBackEvent which take one string argument (You can assign the name to the value of this argument).: 2- 实现System.Web.UI.IPostBackEventHandler.RaisePostBackEvent采用一个字符串参数(您可以将名称分配给此参数的值)。:

public void RaisePostBackEvent(string eventArgument) 
{
        DoSomething(...);
}

3- Write a script to trigger post back: 3-编写脚本以触发回发:

function TriggerPostBack(control, arg){
    __doPostBack(control, arg);
}

4- Call the PostBack trigger function when needed: 4- 需要时调用 PostBack 触发器 function:

<a .... onclick="TriggerPostBack('control', 'arg')" .. /> 

Above answers are generating HTML, if you want to invoke from JavaScript use:以上答案正在生成 HTML,如果您想从 JavaScript 调用,请使用:

__doPostBack('<your controls UniqueID>',''); 

But you will need to have an asp control on your page either way...但是无论哪种方式,您都需要在页面上有一个asp控件...

<script>
    function GO(){
        $("#<%=btnGo.ClientID=%>").click();
    }
</script>

<a id="" href="GO();"">Doit</a>

<asp:Button id="btnGo" onClick="Button1_Click">

i didn't test this, but, this is the basic ideia, if you don't wanna use the LinkButton (that is the best option)我没有对此进行测试,但是,如果您不想使用 LinkButton(这是最好的选择),这是基本的想法

PS: If you are using framework 4.0, you can use the clientid static. PS:如果你使用的是framework 4.0,你可以使用clientid static。 PS2: if want, you can hide the button, but again, the best way to do this is with LinkButton. PS2:如果需要,您可以隐藏按钮,但同样,最好的方法是使用 LinkButton。

EDIT: Are you only trying redirect to another page???编辑:你只是想重定向到另一个页面??? oO???哦???

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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