developer tip

JavaScript를 사용한 ASP.NET 포스트 백

copycodes 2020. 10. 6. 08:25
반응형

JavaScript를 사용한 ASP.NET 포스트 백


draggable div을 활용하는 몇 가지 작은 s가 jQuery있습니다. 이들은 div에 배치되고 UpdatePaneldragstop에서 _doPostBack()JavaScript 함수를 사용합니다 . 페이지 양식에서 필요한 정보를 추출합니다.

내 문제는이 함수를 호출하면 전체 페이지가 다시로드되지만 업데이트 패널 만 다시로드되기를 원한다는 것입니다.


다음은 완전한 솔루션입니다.

asp.net 페이지의 전체 양식 태그

<form id="form1" runat="server">
    <asp:LinkButton ID="LinkButton1" runat="server" /> <%-- included to force __doPostBack javascript function to be rendered --%>

    <input type="button" id="Button45" name="Button45" onclick="javascript:__doPostBack('ButtonA','')" value="clicking this will run ButtonA.Click Event Handler" /><br /><br />
    <input type="button" id="Button46" name="Button46" onclick="javascript:__doPostBack('ButtonB','')" value="clicking this will run ButtonB.Click Event Handler" /><br /><br />

    <asp:Button runat="server" ID="ButtonA" ClientIDMode="Static" Text="ButtonA" /><br /><br />
    <asp:Button runat="server" ID="ButtonB" ClientIDMode="Static" Text="ButtonB" />
</form>

페이지 코드 비하인드 클래스의 전체 내용

Private Sub ButtonA_Click(sender As Object, e As System.EventArgs) Handles ButtonA.Click
    Response.Write("You ran the ButtonA click event")
End Sub

Private Sub ButtonB_Click(sender As Object, e As System.EventArgs) Handles ButtonB.Click
    Response.Write("You ran the ButtonB click event")
End Sub
  • LinkButton은 __doPostBack javascript 함수가 클라이언트에 렌더링되도록하기 위해 포함됩니다. 단순히 Button 컨트롤이 있다고해서이 __doPostBack 함수가 렌더링되지는 않습니다. 이 기능은 대부분의 ASP.NET 페이지에 다양한 컨트롤이 있기 때문에 렌더링되므로 일반적으로 빈 링크 단추가 필요하지 않습니다.

무슨 일이야?

두 개의 입력 컨트롤이 클라이언트에 렌더링됩니다.

<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
  • __EVENTTARGET __doPostBack의 인수 1을받습니다.
  • __EVENTARGUMENT __doPostBack의 인수 2를받습니다.

__doPostBack 함수는 다음과 같이 렌더링됩니다.

function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}
  • 보시다시피 숨겨진 입력에 값을 할당합니다.

양식 제출 / 포스트 백 발생시 :

  • javascript:__doPostBack('ButtonB','')버튼 클릭 처리기 를 실행할 서버 제어 버튼의 UniqueID ()를 제공하면 해당 버튼에 대한 버튼 클릭 처리기가 실행됩니다.

클릭 핸들러를 실행하지 않고 대신 다른 작업을 수행하려면 어떻게해야합니까?

원하는 것은 무엇이든 인수로 전달할 수 있습니다. __doPostBack

그런 다음 숨겨진 입력 값을 분석하고 그에 따라 특정 코드를 실행할 수 있습니다.

If Request.Form("__EVENTTARGET") = "DoSomethingElse" Then
    Response.Write("Do Something else") 
End If

기타 참고 사항

  • 클릭 처리기를 실행할 컨트롤의 ID를 모르는 경우 어떻게합니까?
    • If it is not acceptable to set ClientIDMode="Static", then you can do something like this: __doPostBack('<%= myclientid.UniqueID %>', '').
    • Or: __doPostBack('<%= MYBUTTON.UniqueID %>','')
    • This will inject the unique id of the control into the javascript, should you wish it

Per Phairoh: Use this in the Page/Component just in case the panel name changes

<script type="text/javascript">
     <!--
     //must be global to be called by ExternalInterface
         function JSFunction() {
             __doPostBack('<%= myUpdatePanel.ClientID  %>', '');
         }
     -->
     </script>

While Phairoh's solution seems theoretically sound, I have also found another solution to this problem. By passing the UpdatePanels id as a paramater (event target) for the doPostBack function the update panel will post back but not the entire page.

__doPostBack('myUpdatePanelId','')

*note: second parameter is for addition event args

hope this helps someone!

EDIT: so it seems this same piece of advice was given above as i was typing :)


Using __doPostBack directly is sooooo the 2000s. Anybody coding WebForms in 2018 uses GetPostBackEventReference

(More seriously though, adding this as an answer for completeness. Using the __doPostBack directly is bad practice (single underscore prefix typically indicates a private member and double indicates a more universal private member), though it probably won't change or become obsolete at this point. We have a fully supported mechanism in ClientScriptManager.GetPostBackEventReference.)

Assuming your btnRefresh is inside our UpdatePanel and causes a postback, you can use GetPostBackEventReference like this (inspiration):

function RefreshGrid() {
    <%= ClientScript.GetPostBackEventReference(btnRefresh, String.Empty) %>;
}

If anyone's having trouble with this (as I was), you can get the postback code for a button by adding the UseSubmitBehavior="false" attribute to it. If you examine the rendered source of the button, you'll see the exact javascript you need to execute. In my case it was using the name of the button rather than the id.


Have you tried passing the Update panel's client id to the __doPostBack function? My team has done this to refresh an update panel and as far as I know it worked.

__doPostBack(UpdatePanelClientID, '**Some String**');

First, don't use update panels. They are the second most evil thing that Microsoft has ever created for the web developer.

Second, if you must use update panels, try setting the UpdateMode property to Conditional. Then add a trigger to an Asp:Hidden control that you add to the page. Assign the change event as the trigger. In your dragstop event, change the value of the hidden control.

This is untested, but the theory seems sound... If this does not work, you could try the same thing with an asp:button, just set the display:none style on it and use the click event instead of the change event.


You can't call _doPostBack() because it forces submition of the form. Why don't you disable the PostBack on the UpdatePanel?

참고URL : https://stackoverflow.com/questions/1305954/asp-net-postback-with-javascript

반응형