JQuery Событие Нажатия кнопки asp.net через ajax

См. Спецификации :

Function.prototype.bind (thisArg, ... args)

[...]

[ 116] ПРИМЕЧАНИЕ 1. Функциональные объекты, созданные с помощью Function.prototype.bind, являются экзотическими объектами. Они также не имеют свойства prototype.

BLOCKQUOTE>

33
задан zSynopsis 23 June 2011 в 19:38
поделиться

4 ответа

Здесь jQuery действительно радует разработчиков ASP.Net. Допустим, у вас есть эта кнопка ASP:

Когда это отображается, вы можете посмотреть на источник страницы, и идентификатор на ней будет не btnAwesome, а $ ctr001_btnAwesome или что-то в этом роде. Это затрудняет поиск в javascript. Введите jQuery.

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

Идентификатор $ = выполняет регулярное выражение для идентификатора ENDING с помощью btnAwesome.

Изменить:

Вы хотите, чтобы вызов ajax вызывал из события нажатия кнопки на стороне клиента? Что ты хотел позвонить? Есть много действительно хороших статей об использовании jQuery для выполнения ajax-вызовов кода ASP.Net за методами.

Суть в том, что вы создаете статический метод, помеченный атрибутом WebMethod. Затем вы можете позвонить ему с помощью jQuery, используя $ .ajax.

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

Я изучил свой материал о WebMethod из: http://encosia.com/2008/05/29/using-jquery-to-directly -call-aspnet-ajax-page-methods /

Там много действительно хороших вещей для ASP.Net/jQuery. Убедитесь, что вы прочитали о том, почему вам нужно использовать msg.d в ответах на .Net 3.5 (возможно, начиная с 3.0).

64
ответ дан 27 November 2019 в 17:39
поделиться

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

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.

13
ответ дан 27 November 2019 в 17:39
поделиться

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

$(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();
  }
 }
}
4
ответ дан 27 November 2019 в 17:39
поделиться

ASP.NET web forms page already have a JavaScript method for handling PostBacks called "__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.

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

Then in the ASPX page add a javascript block.

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

The final javascript will be rendered like this.

<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.

10
ответ дан 27 November 2019 в 17:39
поделиться
Другие вопросы по тегам:

Похожие вопросы: