2011-08-17 5 views
29

JavaScript를 사용하여 서버 쪽 C# 메서드를 호출하는 방법을 아는 사람이 있습니까? 내가해야 할 일은 취소가 선택되면 가져 오기를 중지하거나 확인을 선택한 경우 가져 오기를 계속하는 것입니다. 당신은 아약스 내가 의심 호출 할 필요가있을 것이다자바 스크립트를 사용하여 ASP.NET C# 메서드를 호출하는 방법

private void AlertWithConfirmation()    
{     
    Response.Write(
     "<script type=\"text/javascript\">" +  
      "if (window.confirm('Import is currently in progress. Do you want to continue with importation? If yes choose OK, If no choose CANCEL')) {" +  
       "window.alert('Imports have been cancelled!');" +  
      "} else {" + 
       "window.alert('Imports are still in progress');" +  
      "}" +  
     "</script>"); 
} 
+0

아마도 가장 쉬운 방법은 jQuery 또는 관련 프레임 워크를 사용하여 AJAX 요청을 서버로 다시 보내는 것입니다. http://api.jquery.com/jQuery.ajax/ 취소 블록에서 요청을 작성하여 섬기는 사람. 더 많은 정보가 필요하면 그냥 물어보십시오. – timothyclifford

답변

61

PageMethod는 쉽고 빠르게 Asp에 접근합니다.Net AJAX 우리는 AJAX의 힘으로 웹 애플리케이션의 사용자 경험과 성능을 쉽게 향상시킬 수 있습니다. AJAX에서 내가 좋아하는 가장 좋은 것들 중 하나는 PageMethod입니다.

PageMethod는 자바 스크립트에서 서버 측 페이지의 메소드를 노출 할 수있는 방법입니다. 이것은 느리고 성가신 포스트 백을 사용하지 않고도 많은 작업을 수행 할 수있는 많은 기회를 제공합니다.

이 게시물에서는 ScriptManager 및 PageMethod의 기본 사용을 보여줍니다. 이 예에서는 사용자 등록 양식을 작성하여 사용자가 그의 이메일 주소 및 비밀번호에 등록 할 수 있습니다.

<body> 
    <form id="form1" runat="server"> 
    <div> 
     <fieldset style="width: 200px;"> 
      <asp:Label ID="lblEmailAddress" runat="server" Text="Email Address"></asp:Label> 
      <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox> 
      <asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label> 
      <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox> 
     </fieldset> 
     <div> 
     </div> 
     <asp:Button ID="btnCreateAccount" runat="server" Text="Signup" /> 
    </div> 
    </form> 
</body> 
</html> 

설정 페이지 방법에 먼저 페이지에 스크립트 관리자를 드래그해야 : 여기에 내가 개발하기 위하여려고하고 페이지의 마크 업입니다.

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

또한 EnablePageMethods="true"을 변경했습니다.
그러면 ScriptManager에게 클라이언트 측에서 PageMethods를 호출 할 것임을 알립니다.

이제 다음 단계는 서버 측 기능을 만드는 것입니다. '공공 정적이 방법이어야한다 :
먼저 :

[WebMethod] 
public static string RegisterUser(string email, string password) 
{ 
    string result = "Congratulations!!! your account has been created."; 
    if (email.Length == 0)//Zero length check 
    { 
     result = "Email Address cannot be blank"; 
    } 
    else if (!email.Contains(".") || !email.Contains("@")) //some other basic checks 
    { 
     result = "Not a valid email address"; 
    } 
    else if (!email.Contains(".") || !email.Contains("@")) //some other basic checks 
    { 
     result = "Not a valid email address"; 
    } 

    else if (password.Length == 0) 
    { 
     result = "Password cannot be blank"; 
    } 
    else if (password.Length < 5) 
    { 
     result = "Password cannot be less than 5 chars"; 
    } 

    return result; 
} 

이 방법은 우리가 두 가지를 확인해야합니다 자바 스크립트를 통해 액세스 할 수 있는지 스크립트 관리자에게 신고하기 :
여기 내가 만든 기능이며,이 기능은 사용자의 입력을 확인합니다 '.
두 번째 : 위 코드에서 설명한대로 [WebMethod] 태그가 메소드 위에 있어야합니다.

이제 계정을 만드는 서버 측 기능을 만들었습니다. 이제 클라이언트 측에서 호출해야합니다. 여기에서 우리는 클라이언트 측에서 해당 함수를 호출 할 수있는 방법입니다 :

<script type="text/javascript"> 
    function Signup() { 
     var email = document.getElementById('<%=txtEmail.ClientID %>').value; 
     var password = document.getElementById('<%=txtPassword.ClientID %>').value; 

     PageMethods.RegisterUser(email, password, onSucess, onError); 

     function onSucess(result) { 
      alert(result); 
     } 

     function onError(result) { 
      alert('Cannot process your request at the moment, please try later.'); 
     } 
    } 
</script> 

내 서버 측 방법의 등록 사용자를 호출하려면, 스크립트 관리자는 PageMethods에서 사용할 수있는 프록시 기능을 생성합니다.
내 서버 측 함수에는 두 개의 매개 변수, 즉 전자 메일과 암호가 있습니다.이 매개 변수 다음에 메서드가 성공적으로 실행되면 (즉 첫 번째 매개 변수 즉 onSucess) 메서드가 실패하거나 두 번째 매개 변수 즉 결과 인 두 개의 함수 이름을 추가로 제공해야합니다.

이제 모든 것이 준비가 된 것 같습니다. 이제 OnClientClick="Signup();return false;"을 가입 버튼에 추가했습니다. 내 영문 페이지 그래서 여기에 전체 코드 :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <div> 
     <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"> 
     </asp:ScriptManager> 
     <fieldset style="width: 200px;"> 
      <asp:Label ID="lblEmailAddress" runat="server" Text="Email Address"></asp:Label> 
      <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox> 
      <asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label> 
      <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox> 
     </fieldset> 
     <div> 
     </div> 
     <asp:Button ID="btnCreateAccount" runat="server" Text="Signup" OnClientClick="Signup();return false;" /> 
    </div> 
    </form> 
</body> 
</html> 

<script type="text/javascript"> 
    function Signup() { 
     var email = document.getElementById('<%=txtEmail.ClientID %>').value; 
     var password = document.getElementById('<%=txtPassword.ClientID %>').value; 

     PageMethods.RegisterUser(email, password, onSucess, onError); 

     function onSucess(result) { 
      alert(result); 
     } 

     function onError(result) { 
      alert('Cannot process your request at the moment, please try later.'); 
     } 
    } 
</script> 
+3

+ +1 멋진, 이것은 튜토리얼이어야합니다 : D 조 –

+3

+1, 당신은 내 영웅 = D – ch2o

+0

고마워요 @ Fahad, 그러나 나는 오류가 :'Microsoft JScript 런타임 오류 : 'PageMethods'정의되지 않은'... 나를 위해 문제가 마스터 페이지에서 이것을 구현하는 것 같다. –

4

: 나는이 내 코드 내 프로그래밍 lanaguage

으로 비주얼 스튜디오 2010의 C#을 사용하고 있습니다. 다음은 jQuery에서 시작한 Ajax 예제입니다. 코드는 사용자에게 내 시스템에 로그인하지만 성공했는지 여부를 알려줍니다. 코드 숨김 메서드의 ScriptMethod 및 WebMethod 특성에 유의하십시오. 마크 업

:

var $Username = $("#txtUsername").val(); 
      var $Password = $("#txtPassword").val(); 

      //Call the approve method on the code behind 
      $.ajax({ 
       type: "POST", 
       url: "Pages/Mobile/Login.aspx/LoginUser", 
       data: "{'Username':'" + $Username + "', 'Password':'" + $Password + "' }", //Pass the parameter names and values 
       contentType: "application/json; charset=utf-8", 
       dataType: "json", 
       async: true, 
       error: function (jqXHR, textStatus, errorThrown) { 
        alert("Error- Status: " + textStatus + " jqXHR Status: " + jqXHR.status + " jqXHR Response Text:" + jqXHR.responseText) }, 
       success: function (msg) { 
        if (msg.d == true) { 
         window.location.href = "Pages/Mobile/Basic/Index.aspx"; 
        } 
        else { 
         //show error 
         alert('login failed'); 
        } 
       } 
      }); 

뒤에 코드에서 :

/// <summary> 
/// Logs in the user 
/// </summary> 
/// <param name="Username">The username</param> 
/// <param name="Password">The password</param> 
/// <returns>true if login successful</returns> 
[WebMethod, ScriptMethod] 
public static bool LoginUser(string Username, string Password) 
{ 
    try 
    { 
     StaticStore.CurrentUser = new User(Username, Password); 

     //check the login details were correct 
     if (StaticStore.CurrentUser.IsAuthentiacted) 
     { 
      //change the status to logged in 
      StaticStore.CurrentUser.LoginStatus = Objects.Enums.LoginStatus.LoggedIn; 

      //Store the user ID in the list of active users 
      (HttpContext.Current.Application[ SessionKeys.ActiveUsers ] as Dictionary<string, int>)[ HttpContext.Current.Session.SessionID ] = StaticStore.CurrentUser.UserID; 

      return true; 
     } 
     else 
     { 
      return false; 
     } 
    } 
    catch (Exception ex) 
    { 
     return false; 
    } 
} 
0

몇 가지 옵션이 있습니다. 용도에 따라 WebMethod 속성을 사용할 수 있습니다. 내가 바로 가서 당신이 아직없는 경우 라이브러리를 가져와야합니다 의미 jQuery를 사용하는 솔루션을 제공하겠습니다

3

... 당신의 페이지 마크로에서

가져 오기 jQuery 라이브러리 최대 :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script> 

그런 다음 생성 다른 * (그게 노출 것입니다 유일한 방법이기 때문에 내가 ExecutePageMethod를 내 전화) 스크립트 파일 된 .js 그것을 가져옵니다

<script type="text/javascript" src="/ExecutePageMethod.js" ></script> 

function ExecutePageMethod(page, fn, paramArray, successFn, errorFn) { 
    var paramList = ''; 
    if (paramArray.length > 0) { 
     for (var i = 0; i < paramArray.length; i += 2) { 
      if (paramList.length > 0) paramList += ','; 
      paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"'; 
     } 
    } 
    paramList = '{' + paramList + '}'; 
    $.ajax({ 
     type: "POST", 
     url: page + "/" + fn, 
     contentType: "application/json; charset=utf-8", 
     data: paramList, 
     dataType: "json", 
     success: successFn, 
     error: errorFn 
    }); 
} 

그런 다음 해당 속성을 사용하여 .NET 페이지 방식을 확대 할 필요가 : 새로 추가 된 파일 내에서 다음 코드 (나는 다른 곳에서이 당겨 기억, 그래서 다른 사람이 정말 크레딧을받을 권리)을 추가 같은 :

[WebMethod] 
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
public static string MyMethod() 
{ 
    return "Yay!"; 
} 

자, script 블록 내에서 또는 다른 스크립트 파일에서 페이지의 마크 업 내에서, 당신과 같이 메서드를 호출 할 수 있습니다

ExecutePageMethod("PageName.aspx", "MyMethod", [], OnSuccess, OnFailure); 

분명히 OnSuccessOnFailure 메소드를 구현해야합니다.

결과를 얻으려면 OnSuccess 메서드에서 parseJSON 메서드를 사용할 수 있습니다. 결과가 더 복잡해지면 (예를 들어, 형식 배열을 반환하거나)이 메서드는 구문 분석합니다 제품 :

function OnSuccess(result) { 
    var parsedResult = jQuery.parseJSON(result.d); 
} 

ExecutePageMethod 코드는 재사용이 가능한, 그래서보다는 당신이 실행 할 수 있습니다 각 페이지 방법에 대한 $.ajax 전화를 관리해야하는 IT 있기 때문에 특히 유용합니다, 당신은 단지 페이지, 메소드 이름을 통과해야하고 이 메소드의 인수.

+0

이 방법을 사용하려면 페이지에 ScriptManager 도구가 필요합니까? 위의 선택한 대답을 사용할 때 모든 스크립트로드 문제가있는 것 같습니다. –

1

Jayrock RPC library C#을 개발자를위한 좋은 familliar 방법으로이 작업을 수행하는 훌륭한 도구입니다. 이 도구를 사용하면 필요한 메서드로 .NET 클래스를 만들고이 클래스를 스크립트에 추가하여 (로터리 방식으로) 페이지에 추가 할 수 있습니다. 그런 다음 다른 유형의 객체처럼 js 객체를 만들고 메서드를 호출 할 수 있습니다.

기본적으로 ajax 구현을 숨기고 RPC를 familliar 형식으로 제공합니다. ASP.NET MVC를 사용하고 액션 메소드에 jQuery ajax 호출을 사용하는 것이 가장 좋습니다. 훨씬 더 간결하고 덜 복잡합니다!

관련 문제