private void Button1_OnClick(object sender, EventeArgs e)
{
Response.Redirect(myselect.SelectedValue.ToString(), true);
}
Above is my code, I already put a breakpoint on .SelectedValue and it's recognizing the value, but when I click on the button it shows this message:
to do what you need, you must download the file to the client. Response.Redirect as people mentioned redirects to URL.
To make it open in the browser you need the below :
private void Button1_OnClick(object sender, EventeArgs e)
{
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "inline; filename=MyFile.pdf");
Response.TransmitFile(myselect.SelectedValue.ToString());
Response.End();
}
For Content-Disposition you have two choices :
Response.AppendHeader("Content-Disposition", "attachment;filename=somefile.ext") : Prompt will appear for file download
Response.AppendHeader("Content-Disposition", "inline;filename=somefile.ext") : the browser will try to open the file within the browser.
Your sample is assuming that a site e.g. 1.aspx or 221.aspx exists. You are only passing some selected value.
private void Button1_OnClick(object sender, EventeArgs e)
{
Response.Redirect(myselect.SelectedValue.ToString(), true);
}
you need to redirect to some kind of action like:
public FileResult DownloadFile(int id) {
// Your code to retrieve a byte array of your file
var thefileAsByteArray = .....
return File(thefileAsByteArray, System.Net.Mime.MediaTypeNames.Application.Octet, 'DownloadFilenName.pdf');
}
Then you would need to change your onClick metho like:
private void Button1_OnClick(object sender, EventeArgs e)
{
Response.Redirect("Download.aspx?id=" + myselect.SelectedValue.ToString(), true);
}
Related
I am trying to update a label on my windows form with statistics from another methods execution that scrapes a webpage and creates a zip file of the links and creates a sitemap page. Preferably this button would run the scraping operations and report the statistics properly. Currently the scraping process is working fine but the label I want to update with statistics data is not changing on the button click. Here is what my code looks like now:
protected void btn_click(object sender, EventArgs e)
{
//Run scrape work
scrape_work(sender, e);
//Run statistics work
statistics(sender, e);
}
protected void scrape_work(object sender, EventArgs e)
{
//Scraping work (works fine)
}
protected void statistics(object sender, EventArgs e)
{
int count = 0;
if (scriptBox.Text != null)
{
count += 1;
}
var extra = eventsBox.Text;
var extraArray = extra.Split('\n');
foreach (var item in extraArray)
{
count += 1;
}
//scrapeNumLbl is label I want to display text on
scrapeNumLbl.Text = count.ToString();
}
Would I have to use threading for this process or is there some other way I can get this process to work? I have already tried this solution but was having the same issue where the code runs but the label does not update. Any help would be greatly appreciated, this minor thing has been bugging me for hours now.
I eventually solved this by writing the path to the zip file to a label button on the form rather than sending it right to download on the client's browser on button click. The issue was that the request was ending after the zip file was sent for download. To ensure that both methods ran at the proper time I moved the call to the scrape_work method to inside of of statistics
In order for the path to be clickable and the file to download properly I had to make the "label" in the form a LinkButton in the .aspx page
<asp:LinkButton ID="lblDownload" runat="server" CssClass="xclass" OnClick="lblDownload_Click"></asp:LinkButton>
And made the lblDownload_Click run like the following:
Response.Clear();
Response.BufferOutput = false;
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "attachment; filename=zipFiles.zip");
string folder = Server.MapPath("~/zip");
string endPath = folder + "/zipFiles.zip";
Response.TransmitFile(endPath);
Response.End();
Running it this way the page reloads with the new labels properly written and the zip file available to download as well.
ASSUMING THIS CODE IS RUNNING SYNCHRONOUSLY (you aren't threading the scraping in a call I don't see), Are you sure you are reaching the code that sets the label text? I simplified your code as below (removing the iteration over the array and just setting the label text to a stringified integer) and am not having any trouble changing the text of a label.
namespace SimpleTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
scrape_work(sender, e);
statistics(sender, e);
}
protected void scrape_work(object sender, EventArgs e)
{
//Scraping work (works fine)
}
protected void statistics(object sender, EventArgs e)
{
int count = 666;
scrapeNumLbl.Text = count.ToString();
}
}
}
Result:
I am having 2 pages name as :
Abc.aspx
pqr.aspx
Now on page load of Abc.aspx i am doing this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (!string.IsNullOrEmpty(Request.QueryString["Alert"]))
{
if (Request.QueryString["Alert"] == "y")
{
//Here on redirection from Pqr.aspx i will display Javascript alert that your "Your data save"
}
}
else
{
//Dont do anything
}
}
}
Now from pqr.aspx page i am redirecting to Abc.aspx and passing query string on button click:
protected void Save_Click(object sender, EventArgs e)
{
//saving my data to database.
Response.Redirect("~/Abc.aspx?Alert=yes");
}
But what is happening is if anybody enters url like this in browser then still this alert is coming:
http://localhost:19078/Abc.aspx?Alert=yes
Then still this javascript alert box comes.
What i want is after redirecting from my Pqr.aspx page only this alert should come.
How to do this??
In Asp.net there is an object named Request.UrlReferrer.With this property you can get the previous page from which you come to the current page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (!string.IsNullOrEmpty(Request.QueryString["Alert"]))
{
if (Request.QueryString["Alert"] == "y" && Request.UrlReferrer != null && Request.UrlReferrer.LocalPath == "/pqr.aspx") // if the root is same
{
//Here on redirection from Pqr.aspx i will display Javascript alert that your "Your data save"
}
else
{
//Dont do anything
}
}
}
}
I have created a gridView, which contains link buttons with the names.
In the Code Behind file, i wrote following code for download option.
protected void gridview_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Download")
{
String x = "~/Nike_folder/MSR/" + e.CommandArgument.ToString();
string FName = Server.MapPath(x);
Response.Clear();
Response.ContentType = "application/*.*";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + FName);
Response.TransmitFile(FName);
Response.End();
}
}
Once user click on any link, browser window will open and ask for open or save or cancel.
I would like to find out whether the user clicks on Open or save.
Is there any way to find this out?
supposing you have two button in your gridView
var currentButton = sender as Button;
and then currentButton.Text or any property
I have a Master page with an iFrame.
Tickets.aspx has this Master. General.aspx is without any Master and loads inside the iFrame.
Both the pages have buttons to download files.
When downloading file from General.aspx, it shows this error.
Unable to evaluate expression because the code is optimized or a
native frame is on top of the call stack.
General.aspx.cs:
protected void View (object sender, CommandEventArgs e)
{
string sFile = "~/Attachments/"+(e.CommandArgument.ToString());
if(File.Exists(Server.MapPath(sFile)))
{
Response.Redirect("/Forms/DownloadFile.aspx?file="+sFile); //ERROR HERE
}
}
DownloadFile.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
string sPath = Server.MapPath(Request.QueryString["file"]);
FileInfo file = new FileInfo();
if(file.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition","attachment; filename="+file.Name);
Response.AddHeader("Content-Length",file.Length.ToString());
Response.ContentType="application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
}
}
DownloadFile.aspx uses the same Master and has the code. There is no problem when downloading from Tickets.aspx. I thought this could be due to the iframe. So I created a similar download page without a master. But still the same error.
How can I resolve this.
I am using a asyncfileupload control to upload a file there i am taking the path in a view state like this:
protected void ProcessUpload(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string name = System.IO.Path.GetFileName(e.FileName);
string dir = Server.MapPath("upload_eng/");
string path = Path.Combine(dir, name);
ViewState["path"] = path;
engcertfupld.SaveAs(path);
}
Now when i am trying to save that path in a buttonclick event i am not getting the value of viewstate:
protected void btnUpdate_Click(object sender, EventArgs e)
{
string filepath = ViewState["path"].ToString(); // GETTING NULL in filepath
}
In this filepath i am getting null actually i am getting error NULL REFERENCE EXCEPTION
What can I do now?
Put the Path value in the Session object instead of the ViewState, like this:
protected void ProcessUpload(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
....
string path = Path.Combine(dir, name);
Session["path"] = path;
}
Then in the Button Click:
protected void btnUpdate_Click(object sender, EventArgs e)
{
if (Session["path"] != null)
{
string filepath = (string) Session["path"];
}
}
I guess the upload process is not a "real" postback, so the ViewState will not be refreshed client side and won't contain the path upon click on btnUpdate_Click
What you should do is use the OnClientUploadComplete client-side event to retrieve the uploaded file name, and store it in a HiddenField that will be posted on the server on btnUpdate_Click.
Here is a complete example where the uploaded file name is used to display an uploaded image without post-back :
http://www.aspsnippets.com/Articles/Display-image-after-upload-without-page-refresh-or-postback-using-ASP.Net-AsyncFileUpload-Control.aspx