Share via


Call Server side method from Client Side using web method (en-US)

Step 1:  Add meta tag in the Header

We have to add meta tag in the Header of the Document

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>

    

Step 2: Function in Server Side

We have write function in server side like below ,method name should be with webmethod tag like below.

  [System.Web.Services.WebMethod]
 
        public static int UserAccess(string userId,string progId)
 
        {
 
             int userAccess=0;
 
            if(!string.IsNullOrEmpty(progId))
 
            {
 
                UserDataAccessLayer objUsers = new  UserDataAccessLayer ();
 
ContractAccess = objUsers.UserAccess (userId, Convert.ToInt32(progId));
// Write Error Log Here
 
            }
 
            return userAccess;
 
        }

Step 3: Call Method From Server To Client Side

We have to call the server side method from the client side

Step 4:  Add Script Tag

Add Script Tag ,create one variable in as arrary

   <script language="javascript" type="text/javascript">
 
//global Variable to Access in current page
 
   var accessValue;
 
Below method should be here
 
function GetUserAccess()
 
         {            
 
              var progId = document.getElementById("hdnProgId").value;
 
              var userId = document.getElementById("hdnUserId").value;
 
              
 
              $.ajax({
 
                  type: "POST",
 
  
 
                  //Page Name (in which the method should be called) and method name
 
                  url: "Users.aspx/ UserAccess ",
 
                  // If you want to pass parameter or data to server side function you can try line
 
                  data: "{userId:'" + userId + "',progId:'" + progId + "'}",
 
                  //else If you don't want to pass any value to server side function leave the data to blank line below
 
                  //data: "{}",
 
  
 
                  contentType: "application/json; charset=utf-8",
 
  
 
                  dataType: "json",
 
                  
 
                  async: false,
 
  
 
                  success: function(msg) {
 
                      //Got the response from server and render to the client
 
                      accessValue = msg;
 
                  }, error: function(err, req, stat) { alert('error'); }
 
              });             
 
        
 
              return false;
 
      }    
 
</script>

Step 5: Call JavaScript Method In The Normal Javascript Function

Call above javascript method in the Normal javasript function like below.

                  GetUserAccess ();
 
                      if(accessValue>0)
 
                      {
 
If we have any code to do  your work here based on Access
 
                      }
 
                      else
 
                      {
 
                         alert('You are not authorized to view this program');
 
                      }