I am trying to delete an image from a folder by using AJAX and C#. I have created a handler called Delete.ashx to delete the image. I also have an AJAX function to get the image path and pass the path to the handler
In AJAX I have a variable that gets the path which is stored in a textbox (just for now). I make an attempt to pass that path to my handler, however the problem is that the variable in the handler which I am trying to pass the data path to is always empty.
Here is my code:
Handler
public void ProcessRequest(HttpContext context)
{
string sFileName = context.Request["sFileName"]; //this variable is always empty
if (File.Exists(context.Server.MapPath("~/images/" + sFileName)))
{
File.Delete(context.Server.MapPath("~/images/" + sFileName));
context.Response.ContentType = "text/plain";
context.Response.Write("Image deleted Successfully!");
}
else
{
context.Response.ContentType = "text/plain";
context.Response.Write("Image Failed to Delete!");
}
}
AJAX
$(document).ready(function () {
$("#btnDelete").click(function () {
removeFile();
return false;
});
function removeFile() {
var FileName = $("#txtPath").val();
$.ajax({
url: 'Delete.ashx',
type: 'POST',
data: { 'sFileName': FileName},
contentType: false,
processData: false,
success: function (result) {
alert(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}
});
}
});
Please advise how I can pass data from AJAX to the handler so that the variable is not empty. Thank you.
try to get context from current HttpContext:
1
public void ProcessRequest(HttpContext context)
{
var context_= System.Web.HttpContext.Current;
string sFileName = context_.Request["sFileName"];
if (File.Exists(context_.Server.MapPath("~/images/" + sFileName)))
{
File.Delete(context_.Server.MapPath("~/images/" + sFileName));
context_.Response.ContentType = "text/plain";
context_.Response.Write("Image deleted Successfully!");
}
else
{
context_.Response.ContentType = "text/plain";
context_.Response.Write("Image Failed to Delete!");
}
}
2
Or send data with querystring from ajax
modify ajax:
url: 'Delete.ashx?sFileName=blabla',
server side:
var sFileName= Request.Form["sFileName"];
With the help of Mennan I have done the following and is working:
public void ProcessRequest(HttpContext context)
{
string sFileName = context.Request["sFileName"];
if (File.Exists(context.Server.MapPath("~/images/" + sFileName)))
{
File.Delete(context.Server.MapPath("~/images/" + sFileName));
context.Response.ContentType = "text/plain";
context.Response.Write("Image deleted Successfully!");
}
else
{
context.Response.ContentType = "text/plain";
context.Response.Write("Image Failed to Delete!");
}
}
function removeFile() {
var FileName = $("#txtPath").val();
$.ajax({
url: 'Delete.ashx?sFileName=' + FileName,
type: 'POST',
data: { 'sFileName': FileName},
contentType: false,
processData: false,
success: function (result) {
alert(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}
});
}
Related
Currently I am using JQuery AJAX and connect it to the Generic Handler (.ashx), inside the Generic Handler, I am doing the template for the Excel File that is going to save the computer (prompt save). i can achieve that while using the .aspx.cs , the reason I am doing from Generic Handler (.ashx), is because I don't know any way to hide the loading overlay after the dialog box for us to save to the computer is appear. (means the loading overlay just stick there). $(element).show() or $(element).hide() is to show or hide the loading overlay.
I am using EPPlus Library to generate the template for Excel File, however I don't know how to pass the object into client side and then prompt to save, it keeps gives me an error.
The problem I was encountered while using the Generic Handler is always gives me the parsererror message.
Here is the code that I am using:
JQuery AJAX:
var loading = $("#loading");
$("#template").click(function () {
loading.show();
$.ajax({
type: "POST",
url: "TemplateService.ashx?Month=" + $("#Month").val() + "&Year=" + $("#Year").val(),
data: {},
contentType: "application/json",
dataType: "json",
success: function (data) {
loading.hide();
console.log(data);
alert("Success");
},
error: function (xhr, text) {
loading.hide();
console.log(JSON.stringify(xhr.responseText));
console.log(JSON.stringify(text));
alert("There is a problem while processing your request");
}
});
});
Generic Handler (.ashx):
public class TemplateService : IHttpHandler, IRequiresSessionState
{
private int Month = 0;
private int Year = 0;
public void ProcessRequest(HttpContext context)
{
Month = Convert.ToInt32(context.Request.Params["Month"]);
Year = Convert.ToInt32(context.Request.Params["Year"]);
try
{
string MonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(Month);
string fileName = string.Format("{0} - {1} {2}.xlsx", "Excel Template", MonthName, Year);
using (var package = new ExcelPackage())
{
package.Export();
using (var stream = new MemoryStream())
{
context.Response.Clear();
context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName));
package.SaveAs(stream);
stream.WriteTo(context.Response.OutputStream);
context.Response.Write(stream);
}
}
}
catch (Exception)
{
ProcessResponse(context, Response());
}
}
private string Response(bool isSuccess = false)
{
string status = (isSuccess) ? Constant.SUCCESS : Constant.FAILED;
return JsonConvert.SerializeObject(new
{
Status = status
});
}
private void ProcessResponse(HttpContext context, string response)
{
context.Response.Clear();
context.Response.ContentType = "application/json";
context.Response.Write(response);
}
public bool IsReusable
{
get
{
return false;
}
}
}
Export function:
public void Export(this ExcelPackage package)
{
try
{
package.Workbook.Worksheets.Add("Excel Template");
var workSheet = package.Workbook.Worksheets["Excel Template"];
var columnNames = new string[]
{
"First Column",
"Second Column",
"Third Column"
};
var headerRow = new List<string[]>()
{
columnNames
};
var cells = workSheet.Cells[1, 1, 1, 3];
cells.LoadFromArrays(headerRow);
cells.AutoFilter = true;
cells.AutoFitColumns();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
HTML:
<form>
<asp:Button ID="Submission" runat="server" OnClick="Submission_Click" Text="Upload" />
<input type="button" id="Template" value="Template" />
</form>
<script type="text/javascript">
var loading = $("#loading");
$("form").submit(function () {
loading.show();
});
$("#template").click(function () {
loading.show();
$.ajax({
type: "POST",
url: "TemplateService.ashx?Month=" + $("#Month").val() + "&Year=" + $("#Year").val(),
data: {},
contentType: "application/json",
dataType: "json",
success: function (data) {
loading.hide();
console.log(data);
alert("Success");
},
error: function (xhr, text) {
loading.hide();
console.log(JSON.stringify(xhr.responseText));
console.log(JSON.stringify(text));
alert("There is a problem while processing your request");
}
});
});
</script>
Your answer much appreciated.
Thank you.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have an ASP.NET c# page that will post information of form with AJAX in JSON format.
This information includes text of Texboxes and values of Dropdownlists and etc.
Also i need to send a file too.
I have tried the following code and it works fine:
$(".popup-content input:text,.popup-content textarea").each(function () { // Fill object by inputs
objInputs[$(this).attr("name")] = $(this).val();
});
$.ajax({ //Post information
type: "POST",
url: "myAjax.aspx",
data: { func: "Create", information: JSON.stringify(objInputs) /* Convert object to JSON string */ },
success: function (data) { // if sending was successful try to send file
var files = $("#fileImage").get(0).files; //get files form uploadfile
if (files.length > 0) {
var data = new FormData();
data.append(files[0].filename, files[0]);
$.ajax({ //Send file
type: "POST",
url: "Handler1.ashx",
contentType: false,
processData: false,
data: data,
success: function (data) {
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + " " + thrownError);
},
});
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + " " + thrownError);
},
});
But now i want to know if there is a way to send my file along with my JSON?
I found the solution.
The Jquery code should be changed to something like below:
<script>
$(document).ready(function () {
$(document).on("click", "#submit", function () {
var objInputs = {};
objInputs["id"] = "12";
$("#form1 input:text").each(function () { // Fill object by inputs
objInputs[$(this).attr("name")] = $(this).val();
});
var formData = new FormData();
formData.append("information", JSON.stringify(objInputs));
var files = $("#fileupload").get(0).files; //get files form uploadfile
if (files.length > 0) {
for (var i = 0; i < files.length; i++) {
//add each file to the form data and iteratively name them
formData.append("file-" + i, files[i]);
}
$.ajax({ //Send file
type: "POST",
url: "Handler1.ashx",
contentType: false,
processData: false,
data: formData,
success: function (data) {
alert(data)
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + " " + thrownError);
},
});
}
});
});
</script>
And C# code to handling data which was sent (Handler1.ashx):
public void ProcessRequest(HttpContext context)
{
if (context.Request.Files.Count > 0) //To handling files
{
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
if ((files[i].ContentLength < 500000) && (files[i].ContentType == "image/jpeg"))
{
HttpPostedFile file = files[i];
string fname = context.Server.MapPath("~/Images/" + file.FileName);
file.SaveAs(fname);
}
}
context.Response.ContentType = "text/plain";
context.Response.Write("File Uploaded Successfully!");
}
if (!string.IsNullOrEmpty(context.Request["information"])) //To handeling JSON
{
string JSON = context.Request["information"]; //JSON String
}
}
So I'm converting a site form VB to C# and using TypeScript in the process. I have it successfully passing the data to the controller, however the controller post back to the same page instead to the next page.
Here's the TypeScript (full module here)
function formSubmission(submitId, submitUrl, formData, validation) {
if (!submitId || hasSubmit)
return false;
if (validation) {
if (!$("#empApp form").validate().form())
return false;
hasSubmit = true;
}
hasSubmit = true;
// add load status functionality
$(".modal").modal("show");
$.ajax({
type: "POST",
url: submitUrl,
data: formData,
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (response) {
window.location.href = "/employment/application/references";
},
error: function (xhr, ajaxOptions, error) {
$(".modal-body").html("<h3>" + status + "<small>" + error + "</small></h3>");
setTimeout(function () {
$(".modal").modal("hide");
}, 100);
window.location.href = "/employment/application/work-experience";
}
});
}
Here's the Controller (full here)
[HttpPost, Route("Work-Experience")]
public ActionResult WorkExperience(List<EmploymentApplicationWorkExperience> appExperience)
{
EmploymentApplication empAppSession = getApplication();
if (!HasSession()) { return InvalidAppSession(); };
SetupViewBag();
if (!empAppSession.Steps.HasFlag(EmploymentApplication.ApplicationStepTypes.EducationSkills))
{
return PartialView(GetApplicationStepError());
}
if (ModelState.IsValid)
{
if (appExperience != null)
{
empAppSession.ApplicationWorkEperiences = appExperience;
// empAppSession.Application.empApWorkExperiences = (ICollection<empApWorkExperience>)appExperience;
empAppSession.StepCompleted(EmploymentApplication.ApplicationStepTypes.Workexperiences);
updateApplicationStep(empAppSession.Steps);
updateApplicationWorkExpriences(empAppSession.ApplicationWorkEperiences);
updateApplication(empAppSession.Application);
return RedirectToAction("References");
}
return PartialView(GetApplicationView("WorkExperience"), empAppSession.ApplicationWorkEperiences);
}
else
{
return PartialView(GetApplicationView("WorkExperience"), empAppSession.ApplicationWorkEperiences);
}
}
Used a unnecessary filter on Controller that if not valid, would continue to return the current page. Once removed, page continued with out post back issue.
I have verified by using the browser debugger / network monitor that I am sending in a variable in an AJAX call called "search" and in the monitor it shows in the header as "search=test". I am trying to access this variable in the code behind but can't seem to find it? Here is my code for front and back-end, am I missing something?
Code Behind :
public class AJAXSearchLog : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
string searchTerm = Convert.ToString(HttpContext.Current.Request.Form["search"]);
if(!string.IsNullOrEmpty(searchTerm)){
AspDotNetStorefrontCore.DB.ExecuteSQL("insert into TribSearch(SearchTerm,CustomerID,LocaleSetting) values(" + DB.SQuote(CommonLogic.Ellipses(searchTerm, 97, true)) + "," + '0' + "," + DB.SQuote("en-us") + ")");
}
context.Response.Clear();
context.Response.Write(searchTerm);
context.Response.End();
}
public bool IsReusable {
get {
return false;
}
}
}
Front-End
window.onbeforeunload = function(e) {
if ($("#searchBox_text").val().length >= 2) {
var _search = $("#searchBox_text").val();
var url = "/AJAXSearchLog.ashx";
$.ajax({
async: false,
type: 'POST',
url: url,
data: {'search': _search},
contentType: 'application/json;',
dataType: 'json',
success: function(result) {
alert(result);
},
error: function(xhr, textStatus, errorThrown) {
console.log('error');
}
});
}
};
I have found that the data wasn't getting passed through when the contentType was set to 'application/json'. Also, to read the POST variable, Request.Params[] was needed. Here are the 2 lines of code that I changed :
in the front-end -
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
in the back-end -
string searchTerm = Convert.ToString(context.Request.Params["search"]);
I want to download a file using jQuery Ajax web method, but it's not working.
Here is my jQuery ajax call to web method:
function GenerateExcel() {
var ResultTable = jQuery('<div/>').append(jQuery('<table/>').append($('.hDivBox').find('thead').clone()).append($('.bDiv').find('tbody').clone()));
var list = [$(ResultTable).html()];
var jsonText = JSON.stringify({ list: list });
$.ajax({
type: "POST",
url: "GenerateMatrix.aspx/GenerateExcel",
data: jsonText,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
failure: function (response) {
alert(response.d);
}
});
}
and this is the web method definition:
[System.Web.Services.WebMethod()]
public static string GenerateExcel(List<string> list)
{
HttpContext.Current.Response.AppendHeader("content-disposition", "attachment;filename=FileEName.xls");
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.Write(list[0]);
HttpContext.Current.Response.End();
return "";
}
How to get it done?
One more thing: I want to download it on client PC, not to save it on server.
well i have done it using iframe
this is the modified ajax function call
function GenerateExcel() {
var ResultTable = jQuery('<div/>').append(jQuery('<table/>').append($('.hDivBox').find('thead').clone()).append($('.bDiv').find('tbody').clone()));
var list = [$(ResultTable).html()];
var jsonText = JSON.stringify({ list: list });
$.ajax({
type: "POST",
url: "GenerateMatrix.aspx/GenerateExcel",
data: jsonText,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (isNaN(response.d) == false) {
$('#iframe').attr('src', 'GenerateMatrix.aspx?ExcelReportId=' + response.d);
$('#iframe').load();
}
else {
alert(response.d);
}
},
failure: function (response) {
alert(response.d);
}
});
}
and this is the design part
<iframe id="iframe" style="display:none;"></iframe>
on Page load my code looks like this
Response.AppendHeader("content-disposition", "attachment;filename=FileEName.xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.Write(tableHtml);
Response.End();
Add these in your view page-
<iframe id="iframe" style="display:none;"></iframe>
<button id="download_file">Download</button>
Server side
public string Download(string file)
{
string filePath = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["FileManagementPath"]);
string actualFilePath = System.IO.Path.Combine(filePath, file);
HttpContext.Response.ContentType = "APPLICATION/OCTET-STREAM";
string filename = Path.GetFileName(actualFilePath);
String Header = "Attachment; Filename=" + filename;
HttpContext.Response.AppendHeader("Content-Disposition", Header);
HttpContext.Response.WriteFile(actualFilePath);
HttpContext.Response.End();
return "";
}
Add this code in your JavaScript
<script>
$('#download_file').click(function(){
var path = 'e-payment_format.pdf';//name of the file
$("#iframe").attr("src", "/FileCabinet/Download?file=" + path);
});
</script>
That should work!
Assuming the C# code responds with the correct headers for Excel, you can simply redirect to the link instead of using ajax:
var list = [$(ResultTable).html()];
var url = "GenerateMatrix.aspx/GenerateExcel";
var data = {list: list};
url += '?' + decodeURIComponent($.param(data));
// if url is an excel file, the browser will handle it (should show a download dialog)
window.location = url;