简体   繁体   中英

Delete file using jquery ajax in asp.net c#

I have a list of files contains pdf doc txt etc from a folder..and i listed in html format ie filename and delete button in the list(not using gridview). When a user click the delete button file has to delete using ajax not postback method.

Here is my c# code for loading the files.

if (Directory.Exists(path))
       {
           string[] filePaths = Directory.GetFiles(path);
           List<ListItem> files = new List<ListItem>();
           htmlStr = "<table class='tblDocList'><tr class='trDocListHead'><td colspan='3'>Existing Documents</td></tr>";
           foreach (string filePath in filePaths)
           {
               files.Add(new ListItem(Path.GetFileName(filePath), filePath));
               htmlStr += "<tr class='trDataRow'>";
               htmlStr += "<td class='tdFileName'>" + Path.GetFileName(filePath) + "</td>";
               htmlStr += "<td class='tdDownloadLink'><a href class='downloadLink' name='" + filePath + "'>Download</a></td>";
               htmlStr += "<td class='tdDownloadLink'><a href class='deleteLink' name='" + filePath + "'>Delete</a></td>";
               htmlStr += "</tr>";
           }
           htmlStr += "</table>";

        }

Jquery Code

 $('.deleteLink').click(function (e) {
    var fPath = this.name;
    e.preventDefault();
    $.ajax({
        type: "POST",
        url: "Controls/ucAttachDocumentation/DeleteFile",
        data: { fileName: fPath},
        contentType: "application/json",
        success: function (data) {
            alert(data);
        },
        error: function (data) {
            alert(data);
        }
    });
});

In user control for deleteting code

[WebMethod]
   public static bool DeleteFile(string fileName)
   {
       try
       {
           File.Delete(fileName);
           return true;
       }
       catch (Exception e)
       {
           return false;
       }
   }

I am getting the full filepath in jquery and try to call ajax method and it's not working ,can anybody help me out to solve this.

Thanks Alex

This appears to be a syntax/formatting issue. Try the following:

$('.deleteLink').click(function (e) {
    var params = "{'fileName': '" + this.name + "'}";
    e.preventDefault();
    $.ajax({
        type: "POST",
        url: "Controls/ucAttachDocumentation/DeleteFile",
        data: params,
        contentType: "application/json",
        success: function (data) {
            alert(data);
        },
        error: function (data) {
            alert(data);
        }
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM