Search code examples
c#asp.netajaxashx

Delete file from folder - ajax asp.net c#


I am trying to delete file from folder using ajax and Handler.ashx . I have a link when clicked calls removefile() method which further calls method in handler.ashx to delete file. But it is not working. The result returned on success in ajax is always empty and file is not deleted.

Below is the code:

function removeFile(fileName)
        {
            $.ajax({
                 url: 'Handler.ashx/deleteFile',
                type: 'POST',
                data: { 'sFileName': fileName},
                contentType: false,
                processData: false,
                success: function (result) {
                    debugger;
                    alert(result);
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert(xhr.status);
                    alert(xhr.responseText);
                    alert(thrownError);
                }
            });

        }

Below shows the code in Handler.ashx:

public void deleteFile(HttpContext context) {
        string sFileName = context.Request["sFileName"];
        if (File.Exists(context.Server.MapPath("~/Files/" + sFileName)))
        {
            File.Delete(context.Server.MapPath("~/Files/" + sFileName));
            context.Response.ContentType = "text/plain";
            context.Response.Write("File Removed Successfully!");
        }
        else
        {
            context.Response.ContentType = "text/plain";
            context.Response.Write("File Removed Failed!");
        }
    }

Please guide me what am I doing wrong. Thank you in advance


Solution

  • ashx-Handlers aren't called like mvc controllers: there is no mechanism mapping your url onto a method name, so I don't think your deleteFile-method is called at all. You can verify this by setting a breakpoint.

    You should implement a ProcessRequest-method. In this method, you can verify the full url and call your DeleteFile-method (please start .net method names with a capital) with the correct parameters.

    A full explanation on using handlers can be found here: https://www.dotnetperls.com/ashx