Learner Learner - 3 years ago 208
Ajax Question

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)
url: 'Handler.ashx/deleteFile',
type: 'POST',
data: { 'sFileName': fileName},
contentType: false,
processData: false,
success: function (result) {
error: function (xhr, ajaxOptions, 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!");
context.Response.ContentType = "text/plain";
context.Response.Write("File Removed Failed!");

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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download