0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.