Jquery asp.net 按钮点击事件通过ajax

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/855747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:55:57  来源:igfitidea点击:

Jquery asp.net Button Click Event via ajax

jqueryasp.netajaxevents

提问by zSynopsis

I was wondering if anyone can point me in the right direction. I have an asp.net button with a click event (that runs some server side code). What i'd like to do is call this event via ajax and jquery. Is there any way to do this? If so, i would love some examples.

我想知道是否有人可以指出我正确的方向。我有一个带有点击事件的 asp.net 按钮(运行一些服务器端代码)。我想做的是通过 ajax 和 jquery 调用这个事件。有没有办法做到这一点?如果是这样,我会喜欢一些例子。

Thanks in advance

提前致谢

回答by Gromer

This is where jQuery really shines for ASP.Net developers. Lets say you have this ASP button:

这就是 jQuery 真正为 ASP.Net 开发人员发光的地方。假设您有这个 ASP 按钮:

When that renders, you can look at the source of the page and the id on it won't be btnAwesome, but $ctr001_btnAwesome or something like that. This makes it a pain in the butt to find in javascript. Enter jQuery.

当它呈现时,你可以查看页面的源代码,它上面的 id 不会是 btnAwesome,而是 $ctr001_btnAwesome 或类似的东西。这使得在 javascript 中查找变得很麻烦。输入 jQuery。

$(document).ready(function() {
  $("input[id$='btnAwesome']").click(function() {
    // Do client side button click stuff here.
  });
});

The id$= is doing a regex match for an id ENDING with btnAwesome.

id$= 正在为以 btnAwesome 结尾的 id 进行正则表达式匹配。

Edit:

编辑:

Did you want the ajax call being called from the button click event on the client side? What did you want to call? There are a lot of really good articles on using jQuery to make ajax calls to ASP.Net code behind methods.

您是否希望从客户端的按钮单击事件调用 ajax 调用?你想叫什么?有很多关于使用 jQuery 对 ASP.Net 代码背后的方法进行 ajax 调用的非常好的文章。

The gist of it is you create a staticmethod marked with the WebMethod attribute. You then can make a call to it using jQuery by using $.ajax.

它的要点是您创建一个标记有 WebMethod 属性的静态方法。然后,您可以使用 $.ajax 使用 jQuery 调用它。

$.ajax({
  type: "POST",
  url: "PageName.aspx/MethodName",
  data: "{}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg) {
    // Do something interesting here.
  }
});

I learned my WebMethod stuff from: http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/

我从以下位置学习了我的 WebMethod 东西:http: //encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/

A lot of really good ASP.Net/jQuery stuff there. Make sure you read up about why you have to use msg.d in the return on .Net 3.5 (maybe since 3.0) stuff.

那里有很多非常好的 ASP.Net/jQuery 东西。确保你阅读了为什么你必须在 .Net 3.5(也许从 3.0 开始)的回报中使用 msg.d。

回答by Lucas Wilson-Richter

I like Gromer's answer, but it leaves me with a question: What if I have multiple 'btnAwesome's in different controls?

我喜欢 Gromer 的回答,但它给我留下了一个问题:如果我在不同的控件中有多个 'btnAwesome' 怎么办?

To cater for that possibility, I would do the following:

为了迎合这种可能性,我会做以下事情:

$(document).ready(function() {
  $('#<%=myButton.ClientID %>').click(function() {
    // Do client side button click stuff here.
  });
});

It's not a regex match, but in my opinion, a regex match isn't what's needed here. If you're referencing a particular button, you want a precise text match such as this.

这不是正则表达式匹配,但在我看来,这里不需要正则表达式匹配。如果您要引用特定按钮,则需要像这样的精确文本匹配。

If, however, you want to do the same action for every btnAwesome, then go with Gromer's answer.

但是,如果您想对每个 btnAwesome 执行相同的操作,请使用 Gromer 的答案。

回答by Hymansonakj

ASP.NET web forms page already have a JavaScript method for handling PostBacks called "__doPostBack".

ASP.NET Web 表单页面已经有一个用于处理回发的 JavaScript 方法,称为“__doPostBack”。

function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}

Use the following in your code file to generate the JavaScript that performs the PostBack. Using this method will ensure that the proper ClientID for the control is used.

在您的代码文件中使用以下内容来生成执行 PostBack 的 JavaScript。使用此方法将确保为控件使用正确的 ClientID。

protected string GetLoginPostBack()
{
    return Page.ClientScript.GetPostBackEventReference(btnLogin, string.Empty);
}

Then in the ASPX page add a javascript block.

然后在 ASPX 页面中添加一个 javascript 块。

<script language="javascript">
function btnLogin_Click() {
  <%= GetLoginPostBack() %>;
}
</script>

The final javascript will be rendered like this.

最终的 javascript 将像这样呈现。

<script language="javascript">
function btnLogin_Click() {
  __doPostBack('btnLogin','');
}
</script>

Now you can use "btnLogin_Click()" from your javascript to submit the button click to the server.

现在,您可以使用 javascript 中的“btnLogin_Click()”将按钮点击提交到服务器。

回答by Hymansonakj

In the client side handle the click event of the button, use the ClientID property to get he id of the button:

在客户端处理按钮的点击事件,使用ClientID属性获取按钮的id:

$(document).ready(function() {
$("#<%=myButton.ClientID %>,#<%=muSecondButton.ClientID%>").click(

    function() {
     $.get("/myPage.aspx",{id:$(this).attr('id')},function(data) {
       // do something with the data
     return false;
     }
    });
 });

In your page on the server:

在服务器上的页面中:

protected void Page_Load(object sender,EventArgs e) {
 // check if it is an ajax request
 if (Request.Headers["X-Requested-With"] == "XMLHttpRequest") {
  if (Request.QueryString["id"]==myButton.ClientID) {
    // call the click event handler of the myButton here
    Response.End();
  }
  if (Request.QueryString["id"]==mySecondButton.ClientID) {
    // call the click event handler of the mySecondButton here
    Response.End();
  }
 }
}

回答by Kirk Liemohn

I found myself wanting to do this and I reviewed the above answers and did a hybrid approach of them. It got a little tricky, but here is what I did:

我发现自己想要这样做,我查看了上述答案并采用了它们的混合方法。这有点棘手,但这是我所做的:

My button already worked with a server side post. I wanted to let that to continue to work so I left the "OnClick" the same, but added a OnClientClick:

我的按钮已经与服务器端帖子一起使用了。我想让它继续工作,所以我让“OnClick”保持不变,但添加了一个 OnClientClick:

OnClientClick="if (!OnClick_Submit()) return false;"

Here is my full button element in case it matters:

这是我的完整按钮元素,以防万一:

<asp:Button UseSubmitBehavior="false" runat="server" Class="ms-ButtonHeightWidth jiveSiteSettingsSubmit" OnClientClick="if (!OnClick_Submit()) return false;" OnClick="BtnSave_Click" Text="<%$Resources:wss,multipages_okbutton_text%>" id="BtnOK" accesskey="<%$Resources:wss,okbutton_accesskey%>" Enabled="true"/>

If I inspect the onclick attribute of the HTML button at runtime it actually looks like this:

如果我在运行时检查 HTML 按钮的 onclick 属性,它实际上是这样的:

if (!OnClick_Submit()) return false;WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$PlaceHolderMain$ctl03$RptControls$BtnOK", "", true, "", "", false, true))

Then in my Javascript I added the OnClick_Submit method. In my case I needed to do a check to see if I needed to show a dialog to the user. If I show the dialog I return false causing the event to stop processing. If I don't show the dialog I return true causing the event to continue processing and my postback logic to run as it used to.

然后在我的 Javascript 中我添加了 OnClick_Submit 方法。就我而言,我需要检查一下是否需要向用户显示对话框。如果我显示对话框,我将返回 false 导致事件停止处理。如果我不显示对话框,我将返回 true 导致事件继续处理并且我的回发逻辑像以前一样运行。

function OnClick_Submit() {
    var initiallyActive = initialState.socialized && initialState.activityEnabled;
    var socialized = IsSocialized();
    var enabled = ActivityStreamsEnabled();

    var displayDialog;

    // Omitted the setting of displayDialog for clarity

    if (displayDialog) {
        $("#myDialog").dialog('open');
        return false;
    }
    else {
        return true;
    }
}

Then in my Javascript code that runs when the dialog is accepted, I do the following depending on how the user interacted with the dialog:

然后在接受对话框时运行的 Javascript 代码中,我根据用户与对话框的交互方式执行以下操作:

$("#myDialog").dialog('close');
__doPostBack('message', '');

The "message" above is actually different based on what message I want to send.

上面的“消息”实际上根据我要发送的消息而有所不同。

But wait, there's more!

但是等等,还有更多!

Back in my server-side code, I changed OnLoad from:

回到我的服务器端代码,我将 OnLoad 更改为:

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e)
    if (IsPostBack)
    {
        return;
    }

    // OnLoad logic removed for clarity
}

To:

到:

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e)
    if (IsPostBack)
    {
        switch (Request.Form["__EVENTTARGET"])
        {
            case "message1":
                // We did a __doPostBack with the "message1" command provided
                Page.Validate();
                BtnSave_Click(this, new CommandEventArgs("message1", null));
                break;

            case "message2":
                // We did a __doPostBack with the "message2" command provided
                Page.Validate();
                BtnSave_Click(this, new CommandEventArgs("message2", null));
                break;
            }
            return;
    }

    // OnLoad logic removed for clarity
}

Then in BtnSave_Click method I do the following:

然后在 BtnSave_Click 方法中,我执行以下操作:

CommandEventArgs commandEventArgs = e as CommandEventArgs;
string message = (commandEventArgs == null) ? null : commandEventArgs.CommandName;

And finally I can provide logic based on whether or not I have a message and based on the value of that message.

最后,我可以根据我是否有消息以及该消息的价值来提供逻辑。