소프트웨어/C# & ASP.NET

ASP.NET AJAX 와 jquery 의 함께 사용하기 #1

falconer 2009. 5. 19. 11:36
PageMethod 를 직접호출해도 되지만, 번거롭게 jquery 를 사용하는 이유는 뭘까? 왠지 있어보여서 ?
jquery에서 호출할 WebMethod를 선언한다. GetServerDate 메서드는 단순 오늘날짜를 반환하는 기능과 주석을 해제하면 아무 이유없이 서버날짜를 반환못하겠다는 에러를 던져버리는 기능. GetServerObject 는 정말정말 단순한 엔티티 클래스 인스턴스를 반환하는 기능을 정의한다.
01.public partial class TestPageMethod : System.Web.UI.Page
02.{
03.    [WebMethod]
04.    public static string GetServerDate() {
05.        // throw new Exception("서버날짜를 반환하지 못했습니다.");
06.        return DateTime.Today.ToString("yyyy-MM-dd");
07.    }
08.  
09.    [WebMethod]
10.    public static UserAccount GetServerObject() {
11.        return new UserAccount("fivewind", "홍길동");
12.    }
13.    ...
단순 문자열 반환은 언젠가도 포스팅을 했던거 같아서 넘어가고 ... 중요한건 호출이 성공하면 success 함수가 자동으로 호출되고, 실패하면 error 함수가 자동으로 호출된다는것. 생각했던 것보다 .NET Exception 개체정보를 json 형식으로 매우 구체적으로 반환해 준다.
01.$.ajax
02.({
03.    type: "POST",
04.    contentType: "application/json; charset=utf-8",
05.    dataType: "json",
06.    url: "TestPageMethod.aspx/GetServerDate",
07.    data: "{}",
08.    success: function(response)
09.    {
10.        // response.d // 2009-04-24
11.    },
12.    error: function(response) 
13.    {
14.        // response.readyState // 4
15.        // response.status // 500
16.        // response.statusText // Internal Server Error
17.        // eval('(' + response.responseText + ')').ExceptionType // System.Exception
18.        // eval('(' + response.responseText + ')').Message // 서버날짜를 반환하지 못했습니다.
19.        // eval('(' + response.responseText + ')').StackTrace // 위치: TestCase_TestPageMethod.GetServerDate() 파일 i:\Project\TestUnitProject\TestUnitWeb\TestCase\TestPageMethod.aspx.cs:줄 20
20.    }
21.});
UserId, UserName Public 속성을 가진 엔티티클래스의 인스턴스를 json 형식으로 반환한다.
아~ 이런것도 되는구나 정도 ... 이걸 어디다 활용할 수 있을까 ?
01.$.ajax
02.({
03.    type: "POST",
04.    contentType: "application/json; charset=utf-8",
05.    dataType: "json",
06.    url: "TestPageMethod.aspx/GetServerObject",
07.    data: "{}",
08.    success: function(response)
09.    {
10.        // response.d.UserId // fivewind
11.        // response.d.UserName // 홍길동
12.    }
13.});
저작자 표시


출처 : http://fivewind.tistory.com/205