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