IT TIP

OnclientClick과 OnClick이 동시에 작동하지 않습니까?

itqueen 2021. 1. 10. 19:45
반응형

OnclientClick과 OnClick이 동시에 작동하지 않습니까?


다음과 같은 버튼이 있습니다.

<asp:Button ID="pagerLeftButton" runat="server" OnClientClick="disable(this)" onclick="pager_Left_Click" Text="<" />

그런 식으로 버튼을 사용하면 onclick이 실행되지 않습니다. OnClientClick을 제거하면 onclick이 실행됩니다.

내가해야 할 일은 포스트 백 중에 버튼을 비활성화하고 포스트 백이 끝난 후에 활성화하는 것입니다.

편집 : 추가 정보 :

내 실행 기능에 중단 점을 추가 한 것은 C # 부분이며 디버깅 중이며 확실히 실행되지 않습니다. 그 기능은 다음과 같습니다.

protected void pager_Left_Click(object sender, EventArgs e)
{
//Do smthing.
}
protected void pager_Right_Click(object sender, EventArgs e)
{
//Do smthing.
}

내 버튼을 클릭하면 1 ~ 2 초 동안 비활성화되고 자동으로 활성화되지만 활성화 된 이유를 잘 모르겠습니다. 다시 활성화 할 부분을 추가하지 않았습니다.


web.archive.org 의이 기사에서 :

트릭은 버튼 컨트롤의 OnClientClick 및 UseSubmitBehavior 속성을 사용하는 것입니다. 속성을 추가하기 위해 서버 측에 코드를 포함하는 다른 방법이 있지만,이 방법의 단순성이 훨씬 더 매력적이라고 ​​생각합니다.

<asp:Button runat="server" ID="BtnSubmit"  OnClientClick="this.disabled = true; this.value = 'Submitting...';"   UseSubmitBehavior="false"  OnClick="BtnSubmit_Click"  Text="Submit Me!" />

OnClientClick을 사용하면 클라이언트 측 OnClick 스크립트를 추가 할 수 있습니다. 이 경우 JavaScript는 버튼 요소를 비활성화하고 해당 텍스트 값을 진행 메시지로 변경합니다. 포스트 백이 완료되면 새로 렌더링 된 페이지는 추가 작업없이 버튼을 초기 상태로 되돌립니다.

클라이언트 측에서 제출 버튼을 비활성화하는 것과 함께 제공되는 한 가지 함정은 브라우저의 제출을 ​​취소하므로 포스트 백이 취소된다는 것입니다. UseSubmitBehavior 속성을 false로 설정하면 브라우저의 양식 제출 동작에 의존하는 대신 포스트 백을 실행하는 데 필요한 클라이언트 스크립트를 .NET에 삽입하도록 지시합니다. 이 경우 삽입되는 코드는 다음과 같습니다.

__doPostBack('BtnSubmit','')

OnClientClick 코드 끝에 추가되어 렌더링 된 HTML을 제공합니다.

<input type="button" name="BtnSubmit"  onclick="this.disabled = true; this.value ='Submitting...';__doPostBack('BtnSubmit','')"  value="Submit Me!" id="BtnSubmit" />

이것은 포스트 백이 완료되는 동안 멋진 버튼 비활성화 효과와 텍스트 처리를 제공합니다.


OnClientClick은 OnClick과 함께 사용할 때 매우 까다로운 것 같습니다.

다음 사용 사례로 실패했습니다.

OnClientClick="return ValidateSearch();" 
OnClientClick="if(ValidateSearch()) return true;"
OnClientClick="ValidateSearch();"

그러나 그들은 작동하지 않았습니다. 다음은 작동했습니다.

<asp:Button ID="keywordSearch" runat="server" Text="Search" TabIndex="1" 
  OnClick="keywordSearch_Click" 
  OnClientClick="if (!ValidateSearch()) { return false;};" />

Vinay (위)는 효과적인 해결 방법을 제공했습니다. 실제로 OnClientClick 이벤트 기능 이후에 버튼의 OnClick 이벤트가 작동하지 않게하는 원인은 MS가 버튼이 비활성화되면 (OnClientClick 이벤트에 의해 호출되는 기능에서) 버튼이 완료를 시도하지 않음으로써이를 "경양"하는 위치를 정의했기 때문입니다. OnClick 이벤트의 정의 된 메서드를 호출하여 버튼의 활동.

나는 이것을 알아 내려고 몇 시간을 고생했다. 제출 버튼 (OnClientClick 함수 내부에 있음)을 비활성화하는 문을 제거하면 더 이상 문제없이 OnClick 메서드가 호출되었습니다.

Microsoft는 듣고있는 경우 단추를 클릭하면이 활동을 진행하는 동안 비활성화 된 경우에도 할당 된 활동을 완료해야합니다. 클릭 할 때 비활성화되지 않는 한 할당 된 모든 메서드를 완료해야합니다.


여기에는 두 가지 문제가 있습니다.

클라이언트 측에서 버튼을 비활성화하면 포스트 백이 방지됩니다.

이를 극복하려면 JavaScript 이벤트 후에 버튼 비활성화하십시오 onclick. 이를 수행하는 쉬운 방법은 이 답변에서setTimeout 제안한대로 사용 하는 입니다.

또한 OnClientClickASP.NET 유효성 검사가 실패하더라도 코드가 실행되므로 .NET Framework에 대한 검사를 추가하는 것이 좋습니다 Page_IsValid. 이렇게하면 유효성 검사가 실패해도 버튼이 비활성화되지 않습니다.

OnClientClick="(function(button) { setTimeout(function () { if (Page_IsValid) button.disabled = true; }, 0); })(this);"

It's neater to put all of this JavaScript code in its own function as the question shows:

OnClientClick="disable(this);"

function disable(button) {
    setTimeout(function () {
        if (Page_IsValid)
            button.disabled = true;
    }, 0);
}

Disabling the button on the client side doesn't disable it on the server side

To overcome this, disable the button on the server side. For example, in the OnClick event handler:

OnClick="Button1_Click"

protected void Button1_Click(object sender, EventArgs e)
{
    ((Button)sender).Enabled = false;
}

Lastly, keep in mind that preventing duplicate button presses doesn't prevent two different users from submitting the same data at the same time. Make sure to account for that on the server side.


What if you don't immediately set the button to disabled, but delay that through setTimeout? Your 'disable' function would return and the submit would continue.


Your JavaScript is fine, unless you have other scripts running on this page which may corrupt everything. You may check this using Firebug.

I've now tested a bit and it really seems that ASP.net ignores disabled controls. Basically the postback is issued, but probably the framework ignores such events since it "assumes" that a disabled button cannot raise any postback and so it ignores possibly attached handlers. Now this is just my personal reasoning, one could use Reflector to check this in more depth.

As a solution you could really try to do the disabling at a later point, basically you delay the control.disabled = "disabled" call using a JavaTimer or some other functionality. In this way 1st the postback to the server is issued before the control is being disabled by the JavaScript function. Didn't test this but it could work


function UpdateClick(btn) {

    for (i = 0; i < Page_Validators.length; i++) {

        ValidatorValidate(Page_Validators[i]);

        if (Page_Validators[i].isvalid == false)

            return false;
    }

    btn.disabled = 'false';

    btn.value = 'Please Wait...';

    return true;
}

ReferenceURL : https://stackoverflow.com/questions/2155048/onclientclick-and-onclick-is-not-working-at-the-same-time

반응형