Search code examples
c#webmethod

Send values to the database, don't insert duplicates


In need to check if value from TextBox is already in database and if it is not to save it again in the database.

This is the TextBox code:

 <tr>
        <td>
            <asp:Label ID="lblProductConstruction" runat="server" Text="Product Construction:" Font-Names="Open Sans"></asp:Label></td>
        <td>
            <asp:TextBox ID="txtProductConstruction" runat="server"  Font-Names="Merriweather" margin-Left="100px" ></asp:TextBox><br />
        </td>
    </tr>
    <tr>

Save button:

<input type="button" class="button" id="myButton" value="Save"/>

Ajax on button click:

 $(function () {

             $('#myButton').on('click', function () {

                 var lvl = $('#MainContent_txtProductConstruction').val()

                 $.ajax({
                     type: "POST",
                     url: "NewProductConstruction.aspx/GetCollection",

                     data: JSON.stringify({'lvl': lvl }),

                     contentType: "application/json; charset=utf-8",
                     dataType: "json",

                     success: function (response) {
                         alert("Saved successfully.");
                         console.log(response);
                         location.reload(true);

                     },
                     error: function (response) {
                         alert("Not Saved!");
                         console.log(response);
                         location.reload(true);
                     }

                 });

             });

         });

WebMethod that takes the value and sends that parameter(@ObjekatName) to the database:

[WebMethod(EnableSession = true)]
        public static void GetCollection(string lvl)
        {

              string conn = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
            using (SqlConnection connection = new SqlConnection(conn))

                try
                {
                    connection.Open();
                    SqlCommand cmdCount = new SqlCommand("getDuplicate", connection);
                    cmdCount.CommandType = CommandType.StoredProcedure;
                    cmdCount.Parameters.AddWithValue("@ObjekatName", lvl);
                    cmdCount.ExecuteNonQuery();
                    int count = (int)cmdCount.ExecuteScalar();

                    if (count > 0)
                    {
                        connection.Close();
                    }
                    else
                    {
                        SqlCommand cmdProc = new SqlCommand("InsertObjekat", connection);
                        cmdProc.CommandType = CommandType.StoredProcedure;
                        cmdProc.Parameters.AddWithValue("@ObjekatName", lvl);
                        cmdProc.ExecuteNonQuery();
                        //strMsg = "Saved successfully.";
                    }

                }
                catch
                {


                }
                finally
                {
                    connection.Close();

                }

            return;

First procedure is a select that try's to find value in the database. If this select finds something then Count has to be greater than 0 and this should close connection. And if select does not return anything than this new value must be inserted in the database.

I have executed and tested these stored procedures and they work fine. The problem is in C# i think I did something wrong here and this is not working correctly. Can someone help me with c# part ? BTW: Ajax works fine and values are taken by WebMethod correctly

Thanks in advance !


Solution

  • there might be problem with this lines of code

     cmdCount.ExecuteNonQuery();
      int count = (int)cmdCount.ExecuteScalar();
    

    as per this it command two time one executenonquery and then executescalar,

    as per your requirement there should be only one call which is ExecuteScalar, so comment out ExecuteNonQuery

      //cmdCount.ExecuteNonQuery(); comment not needed 
      int count = (int)cmdCount.ExecuteScalar();