상세 컨텐츠

본문 제목

ASP.NET JavaScript <-> C# 함수호출하기 - PageMethod

WEB/JavaScript

by AlrepondTech 2011. 4. 1. 18:43

본문

반응형

 

=================================

=================================

=================================

 

 

 

 

출처: http://www.moros.kr/117

[ASP.NET]
JavaScript 에서 C# 함수호출하기 - PageMethod

JavaScript 에서 C# 함수를 호출하는 방법은
 - ASP.NET AJAX - Web Service 호출
 - ASP.NET Ajax Extentions - PageMethod 호출
 - jQuery를 이용한 WebService 호출
 - Get, Post를 이용한 방법(Non Ajax)
4가지가 있다.

호출 방법에 대해 자세히 참조가 필요 하다면,
참조 : http://blog.naver.com/myfancy/140091157970
를 참조하자.


여기선 ASP.NET Ajax Extentions - PageMethod 호출에
대해서만 간단하게 알아보자.


Ajax 를 통해 PageMethod를 호출하기 위해선

[.aspx 파일]

.aspx 파일에 ScriptManager 를 추가시켜야 한다.

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True">       
    </asp:ScriptManager>

바디 부분에 삽입하자.

* 주의 : EnablePageMethods 속성을 True로 설정하는것을 잊지 말도록 하자!

[.cs 파일]

.cs 파일에서는 평소에 쓰듯이
함수를 만들면 된다.

간단 하게 추가해주어야 할것은
using System.Web.Services;
를 추가하고,

[WebMethod]
    public static string HelloWorld()
    {
        return "Hello World";
    }

함수위에 [WebMethod] 를 추가해준다.

이제 자바 스크립트를 통해 호출해 보도록하자!
자바 함수를 쓰듯이 호출하되
함수 앞에 PageMethods.를 추가하자

PageMethods.HelloWorld();

이해가 가지않는다면
다른 글을 찾아 참조 해보도록하자.
검색검색검색검색! 만이 살길이다!! ^-^

 

 

=================================

=================================

=================================

 

 

 

[ASP.NET] 자바 스크립트 함수 호출방법

자바스크립트 호출한 버튼 하나 만들고...
<asp:Button ID="Button1" runat="server" Text="javascript 호출" onclick="Button1_Click" />
 
디자인단에서
<script>
function Alert(text)
{
alert(text);
}
</script>
이런식으로 자바 스크립트 함수를 body나 head 태그 안에 넣은 다음
 
함수를 호출해야 할 부분에
RegisterClientScriptBlock("중복되지 않는 임의의 문자열", "<script>javascript 호출</script>");
이렇게 넣으면 된다.

 

 

=================================

=================================

=================================

 

한번은 서로 어떻게 호출하는지 정리해둘 필요가 있다고 생각해서..

이 포스트를 쓴다.

 

1. ASP.Net 에서 JavaScript 함수 호출

 

1) ScriptManager.RegisterStartupScript 사용

-.aspx

<script type="text/javascript">
        function AlertMgs(var mgs) {
            alert(msg);  

      }

</script>

-.aspx.cs

ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "AlertMgs('" + sMessage + "');", true);

 

이런식으로 호출이 가능하며 이경우 반드시

<asp:ScriptManager ID="ScriptManager1" runat="server"> 구문이 aspx 페이지에 추가되어 있어야 한다.

 

 

2) Page.ClientScript.RegisterStartupScript 사용

Page.ClientScript.RegisterStartupScript(this.GetType(),  "Alert", "AlertMgs('" + sMessage + "');", true);

이경우

if(!Page.ClientScript.IsStartupScriptRegistered(this.GetType(),  "Alert"))

{

   Page.ClientScript.RegisterStartupScript(this.GetType(),  "Alert", "AlertMgs('" + sMessage + "');", true);

}

이런식으로 스크립트가 등록여부를 알아볼수 있다.

 

3) ScriptManager.RegisterStartupScript vs Page.ClientScript.RegisterStartupScript

이 두가지 중 어느것을 어느경우에 사용하는것이 좋은지 궁금할수도 있겠다.

AJAX 기반-UpdatePanel을 사용할텐데 이럴때는

ScriptManager.RegisterStartupScript를 써야한다.

외국의 포스트들을 봐도 그렇다..

보라->

http://gotjeep.net/Blogs/CommentView,guid,4be2f278-12e4-40d5-b154-0e8ecaf18fac.aspx

 

이참에 좀더 확실하게 2가지 기능을 구별해 보자.

 

[출처: http://msdn.microsoft.com/ko-kr/library/asz8zsxy.aspx]

ClientScriptManager.RegisterStartupScript 메서드 (Type, String, String)

형식, 키 및 스크립트 리터럴을 사용하여 시작 스크립트를 Page 개체에 등록합니다.

 

네임스페이스:  System.Web.UI
어셈블리:  System.Web(System.Web.dll)

구문

public void RegisterStartupScript(
Type type,
string key,
string script
)

매개 변수

type
형식: System.Type
등록할 시작 스크립트의 형식입니다.
key
형식: System.String
등록할 시작 스크립트의 키입니다.
script
형식: System.String
등록할 시작 스크립트 리터럴입니다.
설명

클라이언트 스크립트는 해당 키와 형식에 의해 고유하게 식별됩니다.키 및 형식이 같은 스크립트는 중복된 것으로 간주됩니다.지정된 형식과 키 쌍을 사용하는 스크립트 하나만 페이지에 등록할 수 있습니다.이미 등록된 스크립트를 등록하려고 하면 중복 스크립트가 만들어지지 않습니다.

지정한 키와 형식 쌍으로 시작 스크립트가 이미 등록되어 있는지 여부를 확인하여 스크립트를 추가하려는 불필요한 시도를 방지하려면 IsStartupScriptRegistered 메서드를 호출합니다.

RegisterStartupScript 메서드의 이 오버로드에서는 script 매개 변수에 제공된 스크립트가 <script> 요소 블록으로 래핑되어 있는지 확인해야 합니다.

RegisterStartupScript 메서드가 추가한 스크립트 블록은 페이지에서 로드가 끝날 때 OnLoad 이벤트가 발생하기 전에 실행됩니다.스크립트 블록이 항상 등록된 순서대로 출력되는 것은 아닙니다.스크립트 블록의 순서가 중요한 경우 StringBuilder 개체를 사용하여 스크립트를 단일 문자열로 모은 다음 모든 스크립트를 클라이언트 스크립트 블록 하나에 등록합니다.

예제

다음 코드 예제에서는 RegisterStartupScript 메서드의 사용 방식을 보여 줍니다스크립트 태그의 시작과 종료가 script 매개 변수 내에 포함된다는 점에 유의하십시오.추가 매개 변수 설정을 기반으로 스크립트 태그를 추가하려면, RegisterStartupScript 메서드를 참고하십시오.

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
  public void Page_Load(Object sender, EventArgs e)
  {
    // Define the name and type of the client scripts on the page.
    String csname1 = "PopupScript";
    Type cstype = this.GetType();

    // Get a ClientScriptManager reference from the Page class.
    ClientScriptManager cs = Page.ClientScript;

    // Check to see if the startup script is already registered.
    if (!cs.IsStartupScriptRegistered(cstype, csname1))
    {
        StringBuilder cstext1 = new StringBuilder();
        cstext1.Append("<script type=text/javascript> alert('Hello World!') </");
        cstext1.Append("script>");

        cs.RegisterStartupScript(cstype, csname1, cstext1.ToString());
    }
  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>RegisterStartupScript</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    </div>
    </form>
</body>
</html>
ScriptManager.RegisterStartupScript 메서드 (Page, Type, String, String, Boolean)
ScriptManager 컨트롤을 사용하여 비동기 포스트백이 발생할 때마다 시작 스크립트 블록을 등록하고 페이지에 스크립트 블록을 추가합니다.
 
네임스페이스:  System.Web.UI
어셈블리:  System.Web.Extensions(System.Web.Extensions.dll)
구문

public static void RegisterStartupScript( 	Page page, 	Type type, 	string key, 	string script, 	bool addScriptTags ) 

매개 변수

page
형식: System.Web.UI.Page
클라이언트 스크립트 블록을 등록하는 페이지 개체입니다.
type
형식: System.Type
클라이언트 스크립트 블록의 형식입니다.이 매개 변수는 일반적으로 typeof 연산자(C#) 또는 GetType 연산자(Visual Basic)로 스크립트를 등록하는 컨트롤의 형식을 검색하여 지정됩니다.
key
형식: System.String
스크립트 블록의 고유한 식별자입니다.
script
형식: System.String
스크립트입니다.
addScriptTags
형식: System.Boolean
스크립트 블록을 <script></script> 태그로 묶으면 true이고, 그렇지 않으면 false입니다.
설명

이 메서드는 비동기 포스트백이 발생할 때마다 포함된 시작 스크립트 블록을 등록하는 데 사용합니다.UpdatePanel 컨트롤이 업데이트될 때만 스크립트 블록이 등록되도록 UpdatePanel 컨트롤 내에 있는 컨트롤에 대해 스크립트 블록을 등록하려면 이 메서드의 RegisterStartupScript(Control, Type, String, String, Boolean) 오버로드를 사용합니다.

부분 페이지 업데이트에 속하지 않는 시작 스크립트를 등록하고 해당 스크립트를 초기 페이지 렌더링 시 한 번만 등록하려는 경우 ClientScriptManager 클래스의 RegisterStartupScript 메서드를 사용합니다.ClientScriptManager 개체에 대한 참조는 페이지의 ClientScript 속성에서 가져올 수 있습니다.

 

 

 

반응형

 

728x90

 

 

 

 

2. JavaScript 에서 ASP.Net 메서드 호출

1) WebMethod를 이용하여 메서드 호출

 

-aspx.cs

        public static string CleanUp()
        {
            string response = ConfigurationManager.AppSettings["CloseOutUrl"];
            if (String.IsNullOrEmpty(response))
            {
                response = "ApplicationClosed.aspx";
            }
            return response;
        }

 

-.aspx

function CloseOut(logout) {
            PageMethods.CleanUp(CloseOutResponse, CloseOutResponse);
        }

여기서 중요한 점은....

메소드가 Static 이라는것과

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />

이게 반드시 필요하다는 거심.

 

 

오늘은 여기까지

다음시간에 나머지를 추가해야겠다......

방법: WebMethod 특성 사용

웹 서비스를 클라이언트 스크립트로 노출

 

출처: http://blog.naver.com/ecaface?Redirect=Log&logNo=140109241331

 

=================================

=================================

=================================

 

 

처음에는 웹사이트 개발의 얼개만 소개드릴려고 했는데, 점점 세부기술에 대한 내용을 소개하게 되네요.

hoons 의 삐약이라는 분에게 답변을 하려다보니....

이 블로그에 여기저기에 살짝살짝 나와 있는 내용을 PageMethod 내용으로 정리해 보겠습니다.

 

제 환경은 AJAX Extension 3.5 를 사용했습니다.

script manager 보다는 ToolkitScriptManager를 사용했구요.

 

먼저 페이지에 ToolkitScriptManager를 삽입합니다.

저는 ajax control 들보다 먼저 ToolkitScriptManager를 놓았습니다. (form 시작하자 마자)

그러면 페이지위에

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

로 테그를 쓸수 있게 해주는 지시어라고 해야하나? 이런게 생기구요.

ToolkitScriptManager 가 페이지에 들어가게 됩니다.

PageMethod를 사용할 페이지의 ToolkitScriptManager에만 "EnablePageMethods" attribute을 주었구요.

결과적으로

<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" EnablePageMethods="True">
    </asp:ToolkitScriptManager>

이런 모양이 되었습니다.

 

그냥 페이지의 javascript에서는 pageMethod를 불러서 사용했습니다.

 

PageMethods.getPost(postID, displayPost); 와 같이

displayPost는 pageMethod가 async call 이어서, callback 함수로, page method를 사용한 함수 바로 아래에 정의해 주었습니다.

function displayPost(result) {

   if ( document.getElementById('divPost') != null) {  // 결과가 왔을때 마우스가 움직여서 divPost가 없을 수 있음)
       var view =   document.getElementById('divPost');
       view.innerHTML = result;

   }

}

와 같이...

 

그리고 code behind에 page method를 정의해 줍니다.

[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
    public static string getPost(long postingID)
    {
        blcCom blc = new blcCom();
        return blc.getPost(postingID);
    }

이렇게요. pagemethod의 경우, 반드시 static여야 한다고 합니다.

위의 [System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
 attribute을 쓸려면,


using System.Web.Script.Services;

 

이 추가되어야 하네요.

출처: http://blog.paran.com/junggoportal/43422401

 

=================================

=================================

=================================

 


ASP.NET AJAX의 PageMethods로 같은 페이지의 비하인드 메소드를 호출 할 수 있습니다.
 
{절차}
 
1.  ScriptManager 의 EnablePageMethods 속성을 true로 설정
<asp:ScriptManager ID="ScriptManager1" runat="server" EnableScriptGlobalization="true" EnableScriptLocalization="true" EnablePageMethods="true"></asp:ScriptManager>
 
2. 비하인드 코드 ->  [WebMethod], [ScriptMethod] 어트리뷰트 선언 및 public, static 메소드로 생성
        [WebMethod]
        [ScriptMethod]
        public static bool WishDateCheck(string wishDate)
        {
            //로직
        }
 
3. 자바스크립트에서 호출
        function fn_wishDateCheck(obj)
        {
            currentWishDateObj = obj;
            //메소드 호출은 PageMethods.서버메소드명
            PageMethods.WishDateCheck(obj.value, wishDateCheckCallback);
        }
       
        function wishDateCheckCallback(results, context, methodName)
        {                        
            if(!results)
            {
               //서버 실행 리턴 값에 따른 로직
            }
        }
 
PageMethods 의 보다 자세한 내용은 msdn을 참고하세요.
 
감사합니다.
 
김수영
Visual C# MVP

출처: http://www.hoons.kr/Board.aspx?Name=QACSHAP&Mode=2&BoardIdx=15314&Key=&Value=%20%B3%D7%BF%E4.
 

 

=================================

=================================

=================================

 

 

반응형


관련글 더보기

댓글 영역