Search code examples
javascriptasp.netpagemethods

try catch the pagemethod using javascript


Javascript will call the UploadData function in the server and if it fails to connect to the function it will save into LocalStorage.

How can I catch the error in pagemethod in client-side? I try the below but the catch is not triggered.

 try{
      PageMethods.UploadData(val, onlineSuccess, onlineFailed);
 }catch(e)
 {alert("saved in local");}

Server-side:

 [System.Web.Services.WebMethod]
    public static string UploadData(string text)
    {
        if (text == null || text.Length == 0)
            return String.Empty;

            using (SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["scanner"].ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    string[] data = text.Split('|');

                    cmd.CommandText ="COMMAND HERE"
                    cmd.Connection = cnn;

                    cmd.Parameters.Clear();
                    .................
                    cnn.Open();
                    try
                    {
                        cmd.ExecuteNonQuery();
                        return data[0].ToString()+" saved";
                    }
                    catch (Exception ex)
                    {
                        return "error : "+ex.Message;
                    }
                }
            }
    }

Client-side calling the UploadData function on the server:

function onlineCall(val) {
    //I want to use try-catch here so when it fails to connect to 
    //the server will save in the local storage

    PageMethods.UploadData(val, onlineSuccess, onlineFailed);
}

function onlineSuccess(res, destCtrl) {
    document.getElementById("scanned_item").innerHTML =res;
}

function onlineFailed(res, destCtrl) {
    alert(res);
}

Solution

  • You just need to call this method using ajax and write response in localstorage

     $.ajax({
        url: '/Yourcontroller/UploadData',
        type: 'GET',
        data:{text:"text to pass"},
        success: function (response) {
    
            //do something with response.result
        },
        error: function (response) {
           //write to localstorage response.result
        }
    });
    

    Decorate controller like this

             [HttpGet]
    
    public JsonResult UploadData(string text)
    {
        if (text == null || text.Length == 0)
            return String.Empty;
    
            using (SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["scanner"].ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    string[] data = text.Split('|');
    
                    cmd.CommandText ="COMMAND HERE"
                    cmd.Connection = cnn;
    
                    cmd.Parameters.Clear();
                    .................
                    cnn.Open();
                    try
                    {
                        cmd.ExecuteNonQuery();
                    //    return data[0].ToString()+" saved";
    
    
                 return new JsonResult() { result= data[0].ToString()+" saved", JsonRequestBehavior = JsonRequestBehavior.AllowGet };  
                    }
                    catch (Exception ex)
                    {
                     return new JsonResult() { result= ex.ToString()+" saved", JsonRequestBehavior = JsonRequestBehavior.AllowGet };  
                    }
                }
            }
    }