How to debug JavaScript method in ASP.net


Here are sample of web method, how we can create a web method. Without post back we can call event from client side.
In this way we can avoid Ajax control and simply go for Web Method but sometimes it is very difficult to trace the error in JavaScript.
Here we can just add Firebug (download from internet) to our Mozilla browser and just need to active Firebug and write the [debugger] before the method.

Here is the code:

.aspx Code:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">

        function SaveMe() {
            debugger;
            var firstName = document.getElementById("txtFirstName").value;
            var lastName = document.getElementById("txtLastName").value;

            PageMethods.SaveByWebMethod(firstName, lastName, onSucess, onerror);

            function onSucess(result) {
                alert(result)
            }
            function onerror(result) {
                alert("There is something wrong");
            }
        }

    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="scriptManager" runat="server" EnablePageMethods="true"></asp:ScriptManager>
    <div>
 
    </div>
        <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
        <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
        <asp:Button ID="btnSaveRecord" runat="server" Text="Save" OnClientClick="SaveMe(); return false;" />
    </form>
</body>
</html>

.cs page
    [WebMethod]

    public static string SaveByWebMethod(string firstName, string lastName)
    {
        string result = "Value saved successfully! ";

        try
        {
            SqlConnection dbConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ToString());
            SqlCommand cmd = new SqlCommand("INSERT INTO tblLogin(firstName, lastName) VALUES (@firstName, @lastName)");
            cmd.Parameters.AddWithValue("@firstName", firstName);
            cmd.Parameters.AddWithValue("@lastName", lastName);
            cmd.Connection = dbConn;
            dbConn.Open();
            cmd.ExecuteNonQuery();
            cmd.Dispose();
            dbConn.Close();

            return result;
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }


Hope you will enjoy the topic.

Comments