0

Hi i want to delete all the information of a sql server table with an ajax function, this is my c# method:

[WebMethod]
    public static  void deleteCertificado()
    {
        SqlConnection conn = new 
        SqlConnection(ConfigurationManager.ConnectionStrings["default"].ToString());
        string strsql = "DELETE * FROM Fiel";
        SqlCommand comando = new SqlCommand(strsql, conn);
        comando.CommandTimeout = 36000;
        comando.ExecuteNonQuery();
    }

And my JS function:

function testDel() {
if (confirm('Are you sure you want to delete this?')) {
    $.ajax({
        url: 'Delete.asmx/deleteCertificado',
        type: 'Delete',
        data: {},
        success: function () {
            alert("se borrĂ³");
        }
    });
} else {}

How can i do that? I just want to call the method, my field "data" is empty because i dont have any userid or something like that i just want to DELETE all the info of the table.

1 Answers1

0

First I should point out this previous question. This link is 5 years old and people were saying then that asmx is an old technology and you should be using newer technologies such as web API instead.

Ignoring the above most of the code is there so I assume you are asking what is wrong with it. I see 2 things:

  1. ASMX doesn't handle delete so change your request to a post instead of a delete. I.e. in your jQuery ajax code change type from 'Delete' to 'Post'
  2. Your WebMethod should not be static.

Another I see that would improve things is to use using to ensure that resources are correctly disposed. So I recommend changing your Webmethod to this

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public  void deleteCertificado()
    {
        using (var conn = new
        SqlConnection(ConfigurationManager.ConnectionStrings["default"].ToString()))
        {
            string strsql = "DELETE * FROM Fiel";
            using (var comando = new SqlCommand(strsql, conn))
            {
                comando.CommandTimeout = 36000;
                comando.ExecuteNonQuery();
            }
        }                
    }
Dave Barnett
  • 2,045
  • 2
  • 16
  • 32