Download File with Jquery Ajax - c#

I am using jquery Ajax for downloading PDF file, I generate PDF on runtime and download it,
This is my Ajax call
$.ajax({
async: "false",
type: "POST",
url: "/Reports/DownloadFile?userId=" + encodeURIComponent(userId) + "&date=" + encodeURIComponent(date),
success: function (result) {
}
});
and this is what I am doing in ActionResult
public FileContentResult DownloadFile(int userId, string date, int rptType)
{
var userInfo = UserBLL.GetUserByID(associateId).Name;
var dtFileDate = Convert.ToDateTime(date);
var pdfStream = GeneratePDFStream(userId, date);//Generating Stream
if(date < DateTime.Now)
{
return File(pdfStream, "application/pdf", string.Format("MyReport{0}{1}.pdf", userInfo.Name, dtFileDate.ToShortDateString().Replace("/", "")));
}
return null;
}
but its returning
Sorry, an error occurred while processing your request.
How can I download the file with Ajax call? Please note that I can't use jquery FileDownload but I can do without Ajax call, Kindly suggest
I also tried with this,but same error
var url = "/Reports/DownloadFile?userId=" + encodeURIComponent(userId) + "&date=" + encodeURIComponent(date);
window.open(url);

Instead of ajax call, just try using Iframe as(demo code) :
var url = "/Reports/DownloadFile?userId=" + encodeURIComponent(userId) + "&date=" + encodeURIComponent(date) ;
var $dialog = $('<div></div>')
.html('<iframe style="border: 0px; " src="' + url + '" width="850px" height="100%" scrolling="no"></iframe>')
.dialog({
autoOpen: false,
modal: true,
height: 625,
width: 850,
title: 'YourPdfFile'
});
$dialog.dialog('open');

Related

Web method 404 not found after publishing to production server

The following code is working perfecting after publishing to my localhost. So I copied the files from my localhost and put them on the server. Now it's saying it cannot find the web method. The project is an MVC project and what's not working is an separate aspx page added to the project directory. So, I don't know if this has something to do with IIS. Any ideas would be greatly appreciated.
[WebMethod]
public static string LoadPatients(string phone, string user)
{
//SOME STUFF HERE THAT WAS EXCLUDED//
var sb = new StringBuilder();
for (var x = 0; x < Callerdt.Rows.Count; x++)
{
var addr = Callerdt.Rows[x]["Street"].ToString() + " " + Callerdt.Rows[x]["city"].ToString() + ", " + Callerdt.Rows[x]["State"].ToString() + " " + Callerdt.Rows[x]["ZipCode"].ToString();
sb.AppendFormat("<div class='tabs'><table>" +
"<tr><td class='title'><label>Name:</label></td><td>{0}</td></tr>" +
"<tr><td><label>DOB:</label></td><td>{1}</td></tr>" +
"<tr><td><label>Address:</label></td><td>{2}</td></tr>" +
"<tr><td><label>SSN:</label></td><td>{3}</td></tr>" +
"<tr><td><label>Z Number:</label></td><td>{4}</td></tr>" +
"</table></div><br/>", Callerdt.Rows[x]["Name"].ToString(), Callerdt.Rows[x]["DOB"].ToString(), addr, Callerdt.Rows[x]["SSN"].ToString(), Callerdt.Rows[x]["ZNUM"].ToString());
}
ret = sb.ToString();
return ret;
}
<script type="text/javascript">
$(document).ready(function () {
var p = document.getElementById('pn').value, u = document.getElementById('user').value, er = document.getElementById('error').value;
if (!(er == "true")) {
$("#loading").show();
$.ajax({
type: "POST",
url: 'CallerPopup.aspx/LoadPatients',
data: JSON.stringify({ phone: p, user: u }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('#tabs').append(data.d);
},
complete: function () {
$("#loading").hide();
}
});
}
});
</script>
In my case, adding IgnoreRoute to RegisterRoutes() got me going. Now the aspx.cs "static" hosted [webmethod] loads ... url: 'LearnKO.aspx/FetchStudents',
aJax was throwing a 404 - Not Found on any page.aspx/webmethod call.
ie. the fix:
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
I was setting up http://www.c-sharpcorner.com/UploadFile/1492b1/learning-knockout-part-1-introduction-to-knockout-js-and-cr/ in an MVC project instead of the recommended empty ASP.NET... my bad.

Using uploadify with ashx handler

Hi friends i have a form in which there are some text boxes, drop downs and as well as image . I am using knock out js to save the form details. And i am using uploadify plugin to upload my image to a local folder .I have implemented all this things but when it comes to saving the values till now i used a aspx code behind . For uploading purpose we had to choose ashx. So it will be like two server side postings going to happen!!
So i would like to save my data in ashx page rather than aspx.
But i am confused where exactly to start my upload..please some one help me with this!!!
i am saving my values in a save button event like below!!
self.AddEvent = function (args) {
// Here--> $('#file_upload').uploadify('upload');
ajax.Post("../Scripts/uploadify/UploadHandler.ashx", JSON.stringify({ objEnt: args }), false).success(function (data) {
if (data.d[0] > 0) {
// or Here--> $('#file_upload').uploadify('upload');
alert('success');
}
and my fileupload setting s are:
$('#file_upload').uploadify({
'swf': '../Scripts/uploadify/uploadify.swf',
'uploader': '../Scripts/uploadify/UploadHandler.ashx',
'method': 'post',
'formData': { 'someKey': Filename },
'buttonText': 'Browse',
'auto': false,
'folder': 'upload',
'fileTypeExts': '*.jpg;*.jpeg;*.gif;*.png',
'onSelect': function (file) {
var ext = file.name.split('.').pop();
$("#filename").val(Filename + '.' + ext);
},
'onUploadSuccess': function (file, data, response) {
if (response == true) {
$("#eventGrid").jqxGrid('updatebounddata');
}
}
});
It is not possible to call self.AddEvent in 'onUploadsuccess' in my situation...!!!
Please suggest me some best way to store my data and image at same time in ashx handler.
ashx:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
var data = context.Request;
var sr = new StreamReader(data.InputStream);
var stream = sr.ReadToEnd();
var javaScriptSerializer = new JavaScriptSerializer();
var asd = javaScriptSerializer.Deserialize<RootObject>(stream);
string Newname = context.Request.Form["someKey"];
BAL Bl = new BAL();
string[] args = new string[2];
//AddEvent method will add my data into database add return response "Success"//
args = AddEvent(asd.objEnt);
HttpPostedFile PostedFile = context.Request.Files["Filedata"];
string ext = Path.GetExtension(PostedFile.FileName);
string savepath = "";
string temppath = "";
temppath = System.Configuration.ConfigurationManager.AppSettings["FolderPath"];
savepath = context.Server.MapPath(temppath);
string fileName = Newname + ext;
if (!Directory.Exists(savepath))
Directory.CreateDirectory(savepath);
PostedFile.SaveAs(savepath + #"\" + fileName);
context.Response.Write(temppath + "/" + fileName);
// context.Response.Write(args);
context.Response.StatusCode = 200;
}
}
$("#<%=FileUpload1.ClientID%>").uploadify({
'uploader': 'Upload.ashx',
'swf': 'uploadify/uploadify.swf',
'script': 'Upload.ashx',
'cancelImg': 'images/cancel.png',
'folder': '../Upload',
'multi': true,
'buttonText': 'select picture',
'fileExt': '*.jpg;*.png;*.gif;*.bmp;*.jpeg',
'auto': false,
'onUploadStart': function () {
}
});
$.ajax({
type: "POST",
url: 'WebServiceAdmin.asmx/SaveData',
data: "{'p':'" + datam+ "'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (d) { $('#FileUpload1').uploadify('upload', '*'); },
error: function () { }
});

Posting JSON object to asp.net server

i am trying to post some json data to to my asp.netserver on my localhost. The page to receive the code should be the master page, however i tried that and got "Error 403: Forbidden" so i tried my hands on a web service instead and now i am having a whole load of other issues. My main issue is that i could do this rather simply in PHP but i have no idea how to go about this in ASP.NET.
This is my js file:
// Get User Login Credentials
function authenticate() {
$(document).ready(function () {
var user = $('.login-box form #txtLoginUsername').val().trim();
var pass = $('.login-box form #txtLoginPass').val().trim();
// alert(user + " : " + pass);
$.ajax({
type: "POST",
url: "postback.asmx/Verify",
data: {
user: user,
pass: pass
},
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function() {
if (response)
{
alert('Works');
}
else {
$(".ui-widget").slideDown(1000, function () {});
}
}
});
});
}
Now i call this function on a button click event, i do not add my server code because it comprises of several lines of code i picked up from the net and tried to mash up to get my page to work, which it didn't. I would like to know a simple appropriate method of getting JSON objects from a post and return a value/array from my server.
Please i do not wish to use any asp.net server controls for certain reasons i am unable to disclose, but i have been restricted from using such controls.
You can´t put your WebMethod in an masterPage. Ajax is client side and you are getting the same error if you tried to acess site.master in your browser.
"Description: The type of page you have requested is not served because it has been explicitly forbidden. The extension '.master' may be incorrect. Please review the URL below and make sure that it is spelled correctly. "
You can implement your WebMethod in other file .aspx and call by ajax.
I wrote an little example.
cs
[WebMethod(enableSession: true)]
public static void Verify(string user, String pass)
{
throw new Exception("I´m here");
}
js
function authenticate() {
$(document).ready(function () {
var user = $('#txtLoginUsername').val().trim();
var pass = $('#txtLoginPass').val().trim();
// alert(user + " : " + pass);
var data = {};
data.user = user;
$.ajax({
type: "POST",
url: "default.aspx/Verify",
data: JSON.stringify({
user: user,
pass: pass
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
if (response) {
alert('Works');
}
else {
$(".ui-widget").slideDown(1000, function () { });
}
}
});
});
}
pay attention how Json is passing to data
data: JSON.stringify({
user: user,
pass: pass
}),
To call webservice, try pass json this way.
When you call web service there are same error message in browser´s console?
I think this is will help you.
You can use JSON.stringify() method as explained in follow
var jsonData=your Jason data;
Data:JSON.stringify(jsonData)
courtsey:
http://www.dotnetlines.com/forum/tabid/86/forumid/6/postid/72/scope/posts/Default.aspx#72
You can do like this.
[WebMethod]
public string Verify(string user,string pass)
{
//DataTable dt = YourMethod_ReturningDataTable();
//retrun dt.toJson();
//But in your case
bool IsAllowedtoLogin = true;
return IsAllowedtoLogin.toJson();
}
For this (toJson) method you have create a static class.This will convert even datatable to json format.
public static string toJson(this DataTable dataTable)
{
string[] StrDc = new string[dataTable.Columns.Count];
string HeadStr = string.Empty;
for (int i = 0; i < dataTable.Columns.Count; i++)
{
StrDc[i] = dataTable.Columns[i].Caption;
HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";
}
HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);
StringBuilder Sb = new StringBuilder();
Sb.Append("{\"" + dataTable.TableName + "\" : [");
for (int i = 0; i < dataTable.Rows.Count; i++)
{
string TempStr = HeadStr;
Sb.Append("{");
for (int j = 0; j < dataTable.Columns.Count; j++)
{
TempStr = TempStr.Replace(dataTable.Columns[j] + j.ToString() + "¾", dataTable.Rows[i][j].ToString());
}
Sb.Append(TempStr + "},");
}
Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
Sb.Append("]}");
return Sb.ToString();
}
Note that data parameters are case sensitive. i.e user , pass .
$.ajax({
type: "POST",
url: "default.aspx/Verify",
data: "{'user':'"+yourvariable+"','pass':'"+yourvariable+"'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
data = JSON && JSON.parse(data.d) || $.parseJSON(data.d);
if (data == "true") {
alert('Works');
}
else {
$(".ui-widget").slideDown(1000, function () { });
}
}
});

Form submit cancels jQuery ajax call

I have a Generic Handler (DownloadHandler.cs) which serves as both generating a pdf and downloading a pdf. When generating I use a jQuery ajax call and when downloading I use a form element which is submitted. The problem is that the form element cancels the generate request and therefore the "success" event never gets called (See image below).
Generate code (Gets called from a button):
$.ajax({
type: "POST",
url: "/DownloadHandler.ashx",
data: {
GeneratePdf: true
},
success: function (result) {
console.log(result);
},
error: function (errorMessage) {
console.log(errorMessage);
}
});
Download code (Gets called from a button):
var data = { "GeneratePdf": false }
var inputs = '';
$.each(data, function (key, value) {
inputs += '<input type="hidden" name="' + key + '" value="' + value + '" />';
});
$('<form action="/DownloadHandler.ashx" method="POST">' + inputs + '</form>').appendTo('body').submit().remove();
DownloadHandler:
public void ProcessRequest(HttpContext context)
{
if (!String.IsNullOrEmpty(context.Request["GeneratePdf"]) && Convert.ToBoolean(context.Request["GeneratePdf"]))
{
Thread.Sleep(3000);
context.Response.Clear();
context.Response.Write("GENERATING");
context.Response.Flush();
}
else
{
Thread.Sleep(3000);
FileInfo pdfFile = new FileInfo(#"C:\1.pdf");
context.Response.Clear();
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + pdfFile.Name);
context.Response.AddHeader("Content-Length", pdfFile.Length.ToString());
context.Response.ContentType = "application/octet-stream";
context.Response.WriteFile(pdfFile.FullName);
context.Response.Flush();
}
}
public bool IsReusable
{
get
{
return false;
}
}
I just added a Thread.Sleep to demonstrate the generation of the pdf. Am I missing something or should I use some other method?
Maybe you can try targetting a tiny dynamic iframe on your page with your form. Something like :
var data = { "GeneratePdf": false }
var inputs = '';
$.each(data, function (key, value) {
inputs += '<input type="hidden" name="' + key + '" value="' + value + '" />';
});
var f = $('<form action="/DownloadHandler.ashx" method="POST">' + inputs + '</form>');
var iframe = $('<iframe src="about:blank"/>') // should be made tiny/transparent with some css
.appendTo('body');
iframe.contents().find('html').append(f);
f.submit().remove();

file upload using jquery ajax

I want to upload a image with a description like:
data = '{"filename":"' + myfilename + '", "file":"' + file + '", "description":"' +
description + '"}';
$.ajax({
type: "POST",
url: "filehandler.ashx",
data: data,
success: function (result) {
alert(result);
},
error: function () {
alert("There was error uploading file!");
}
});
how can I do it? I can't read file as HttpPostedFile in generic handler.
context.Request.Form also doesn't have any keys.
I'm sorry, If I not posted fully what I did in question. Anyway I got it to work.
var data = new FormData();
data.append("name", filename);
data.append("file", file);
In generic handler
HttpPostedFile file = context.Request.Files["file"];
string fileName = context.Request.Form["filename"];
Using FormData Objects
you cant post files with ajax you have to post it in a iframe to have the same result
this is what I did
var form = "#myform";
var url = "http://post.it/";
var iframeName = 'iframePost' + (new Date()).getTime();
$('<iframe id="'+iframeName+'" name="' + iframeName + '" style="display:none;"/>').appendTo('body');
$(form).attr('target',iframeName)
.attr('action',url)
.attr('enctype','multipart/form-data')
.append('<input type="hidden" name="_iframe" value="' + iframeName + '" />');
form.submit();
to have a callback let the iframe return a script with something like
window.parent.callBack(data);

Categories

Resources