Reputation: 1051
I have tried many articles on net for downloading a text file using JQuery, Ajax and C#. Most of them says you cannot download file using ajax.
Here is my JQuery-Ajax code
$(document).on("click", "#imgDownload", function (event) {
$.ajax({
url: "/members/DownloadSelectedFile?SelectedUserName=" + $("#AllowedFriends").find(":selected").text() + "&SelectedFileName=" + $(this).siblings("span").eq(0).text(),
success: function () {
alert("Khushi");
}
});
});
Here is my C# code
public void DownloadSelectedFile(string SelectedUserName, string SelectedFileName)
{
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "Filename=" + SelectedFileName + ".txt");
Response.TransmitFile(Server.MapPath("~/Users/" + SelectedUserName + "/" + (string)Session["LoggedInUserName"] + "/" + SelectedFileName + ".txt"));
Response.End();
}
So, what are the changes that I need to make to be able to download a text file.
Upvotes: 0
Views: 4696
Reputation: 3281
Add an IFrame to your document, either runat=server or not.... The following example requires you keep it client
<iframe id="myDownloaderFrame" style="display:none;" ></iframe>
$(document).on("click", "#imgDownload", function (event) {
$("#myDownloaderFrame").attr("src","/members/DownloadSelectedFile?SelectedUserName=" + $("#AllowedFriends").find(":selected").text() + "&SelectedFileName=" + $(this).siblings("span").eq(0).text());
});
Upvotes: 4