program story

ASP : CheckBox에 대한 OnClick 대 OnClientClick?

inputbox 2020. 9. 22. 08:11
반응형

ASP : CheckBox에 대한 OnClick 대 OnClientClick?


asp : CheckBox에 대한 클라이언트 측 자바 스크립트 핸들러가 asp : Button과 같이 OnClientClick = ""속성이 아닌 OnClick = ""속성이어야하는 이유를 아는 사람이 있습니까?

예를 들어 다음과 같이 작동합니다.

<asp:CheckBox runat="server" OnClick="alert(this.checked);" />

그리고 이것은 (오류 없음) :

<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />

그러나 이것은 작동합니다.

<asp:Button runat="server" OnClientClick="alert('Hi');" />

그리고 이것은 (컴파일 시간 오류) :

<asp:Button runat="server" OnClick="alert('hi');" />

(Button.OnClick이 무엇인지 알고 있습니다. 왜 CheckBox가 같은 방식으로 작동하지 않는지 궁금합니다 ...)


그것은 매우 이상합니다. 나는 CheckBox 문서 페이지확인했습니다.

<asp:CheckBox id="CheckBox1" 
     AutoPostBack="True|False"
     Text="Label"
     TextAlign="Right|Left"
     Checked="True|False"
     OnCheckedChanged="OnCheckedChangedMethod"
     runat="server"/>

보시다시피 OnClick 또는 OnClientClick 속성이 정의되어 있지 않습니다.

이것을 염두에두고 이것이 일어나고 있다고 생각합니다.

이렇게하면

<asp:CheckBox runat="server" OnClick="alert(this.checked);" />

ASP.NET은 OnClick 특성을 수정하지 않고 브라우저에서 그대로 렌더링합니다. 다음과 같이 렌더링됩니다.

  <input type="checkbox" OnClick="alert(this.checked);" />

분명히 브라우저는 'OnClick'을 이해하고 경고를 표시합니다.

그리고이 시나리오에서

<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />

다시 말하지만 ASP.NET은 OnClientClick 특성을 변경하지 않고 다음과 같이 렌더링합니다.

<input type="checkbox" OnClientClick="alert(this.checked);" />

브라우저가 OnClientClick을 이해하지 못하므로 아무 일도 일어나지 않습니다. 또 다른 속성이므로 오류가 발생하지 않습니다.

렌더링 된 HTML을 보면 위에서 확인할 수 있습니다.

그리고 예, 이것은 전혀 직관적이지 않습니다.


두 종류의 컨트롤이기 때문에 ...

웹 브라우저는 서버 측 프로그래밍에 대해 알지 못합니다. 자체 DOM과 사용하는 이벤트 모델에 대해서만 알고 있습니다. 그리고 렌더링 된 객체의 클릭 이벤트에 대해서도 알고 있습니다. ASP.Net에서 브라우저로 실제로 전송 된 최종 마크 업을 검사하여 차이점을 확인해야합니다.

<asp:CheckBox runat="server" OnClick="alert(this.checked);" />

렌더링

<input type="check" OnClick="alert(this.checked);" />

<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />

렌더링

<input type="check" OnClientClick="alert(this.checked);" />

Now, as near as i can recall, there are no browsers anywhere that support the "OnClientClick" event in their DOM...

When in doubt, always view the source of the output as it is sent to the browser... there's a whole world of debug information that you can see.


You are right this is inconsistent. What is happening is that CheckBox doesn't HAVE an server-side OnClick event, so your markup gets rendered to the browser. http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.checkbox_events.aspx

Whereas Button does have a OnClick - so ASP.NET expects a reference to an event in your OnClick markup.


For those of you who got here looking for the server-side OnClick handler it is OnCheckedChanged


I was cleaning up warnings and messages and see that VS does warn about it: Validation (ASP.Net): Attribute 'OnClick' is not a valid attribute of element 'CheckBox'. Use the html input control to specify a client side handler and then you won't get the extra span tag and the two elements.


You can do the tag like this:

<asp:CheckBox runat="server" ID="ckRouteNow" Text="Send Now" OnClick="checkchanged(this)" />

The .checked property in the called JavaScript will be correct...the current state of the checkbox:

  function checkchanged(obj) {
      alert(obj.checked)
  }

Asp.net CheckBox is not support method OnClientClick.
If you want to add some javascript event to asp:CheckBox you have to add related attributes on "Pre_Render" or on "Page_Load" events in server code:

C#:

    private void Page_Load(object sender, EventArgs e)
    {
        SomeCheckBoxId.Attributes["onclick"] = "MyJavaScriptMethod(this);";
    }

Note: Ensure you don't set AutoEventWireup="false" in page header.

VB:

    Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        SomeCheckBoxId.Attributes("onclick") = "MyJavaScriptMethod(this);"
    End Sub

One solution is with JQuery:

$(document).ready(
    function () {
        $('#mycheckboxId').click(function () {
               // here the action or function to call
        });
    }
);

참고URL : https://stackoverflow.com/questions/1135134/onclick-vs-onclientclick-for-an-aspcheckbox

반응형