When you have button to export excel or csv file format, saving file will not working if you are using UpdatePanel. It will show following message when you debug.
Message: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled. Details: Error parsing near '
Cause:
The action that causes this code to execute MUST be a postback event, and not an AJAX call.
This is due to the nature of the way AJAX requests are processed.
Solution:
1: Put button outside UpdatePanel (or)
2: Add following code in PageLoad of you aspx page
((ScriptManager)Master.FindControl("ToolkitScriptManagerID")).RegisterPostBackControl(btnExport)
Download csv example
protected void btnExport_Click(object sender, EventArgs e)
{
if (ListUser != null)
{ //Build the CSV file data as a Comma separated string.
string csv = string.Empty;
csv = "\"Login ID\",\"Nav Customer No.\",\"Login Time\",\"Logout Time\"";
//Add new line.
csv += "\r\n";
string logouttime;
foreach (LoginHistory user in ListUser)
{
logouttime = user.LogOutTime == null ? "" : Convert.ToDateTime(user.LogOutTime).ToString("dd/MM/yyyy hh:mm:ss tt");
csv += "\"" + user.UsrName + "\",\"" + user.CustomerCode + "\",\"" + user.Logintime.ToString("dd/MM/yyyy hh:mm:ss tt") + "\",\"" + logouttime + "\"";
//Add new line.
csv += "\r\n";
}
//Download the CSV file.
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=LoginHistory_" + DateTime.Now.ToString("ddMMyyyyHHmmss") + ".csv");
Response.Charset = "";
Response.ContentType = "application/text";
Response.Output.Write(csv);
Response.Flush();
Response.End();
}
}
Download csv example
protected void btnExport_Click(object sender, EventArgs e)
{
if (ListUser != null)
{ //Build the CSV file data as a Comma separated string.
string csv = string.Empty;
csv = "\"Login ID\",\"Nav Customer No.\",\"Login Time\",\"Logout Time\"";
//Add new line.
csv += "\r\n";
string logouttime;
foreach (LoginHistory user in ListUser)
{
logouttime = user.LogOutTime == null ? "" : Convert.ToDateTime(user.LogOutTime).ToString("dd/MM/yyyy hh:mm:ss tt");
csv += "\"" + user.UsrName + "\",\"" + user.CustomerCode + "\",\"" + user.Logintime.ToString("dd/MM/yyyy hh:mm:ss tt") + "\",\"" + logouttime + "\"";
//Add new line.
csv += "\r\n";
}
//Download the CSV file.
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=LoginHistory_" + DateTime.Now.ToString("ddMMyyyyHHmmss") + ".csv");
Response.Charset = "";
Response.ContentType = "application/text";
Response.Output.Write(csv);
Response.Flush();
Response.End();
}
}
No comments:
Post a Comment