Call alert after response.end - javascript

Here is my code where I am trying to show alert after response. But no os alert is showing
string filepath = ConfigurationManager.AppSettings["USPPath"].ToString() + urlPDF;
FileInfo file = new FileInfo(Server.MapPath(filepath));
if (file.Exists)
{
ClientScript.RegisterStartupScript(this.GetType(), "somekey", "alert('Some data missing!');", true);
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/pdf";
Response.TransmitFile(file.FullName);
try
{
Response.Flush();
ClientScript.RegisterStartupScript(this.GetType(), "somekeyqw","alert('Some data missing!'); ", true);
// DisplaySucessAlert(true, "Shipping Label downloaded successfully.");
// ScriptManager.RegisterStartupScript(this, this.GetType(), "Popalertxs", "normalalert();", true);
}
finally
{
// DisplaySucessAlert(true, "Shipping Label downloaded successfully.");
// ScriptManager.RegisterStartupScript(this, this.GetType(), "Popalert", "normalalert();", true);
}
}
I have used update panel and the html code look likes
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="btnuspsgenerate" class="btn-def" runat="server" Text="Download USPS label" OnClick="btnuspsgenerate_Click" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnuspsgenerate" />
</Triggers>
</asp:UpdatePanel>
My pdf file gets download but not showing alert.
Here I had used many ways but not able to show alert.
Some of the code I have commented as they where not working

When you use update panel then you can not call javascript like this ..
Try Following Code,
string CloseWindow;
CloseWindow = "alert('Hello World')";
ScriptManager.RegisterStartupScript(UpdatePanelID,UpdatePanelID.GetType(), "CloseWindow", CloseWindow, true);

Related

ASP.NET download PDF feature in UpdatePanel unable to refresh UpdateProgress control

I've two UpdatePanel in a page. The second one has UpdateMode="Conditional" and here there's a link button to produce PDF file.
My goal is to allow the PDF download and in the meantime make a waiting image appear (like an hourglass).
After a few days of studying I reached my goal but i can't hide the image after all operations are terminated.
In the code example i've simplified logic to procude pdf (in complete code i use gridview control data to produce pdf).
If I use an asynchronous PostBackTrigger in UpdatePanel the PDF is not downloaded even if the UpdateProgress (with the expected image) works correctly.
If I use a Synchronous PostBackTrigger in UpdatePanel the PDF is downloaded correctly but the updateProgress does not work because the waiting image remains on the screen. In this case i've used a client side function (postbackButtonClick) to display the image.
I've read many threads but each one is always a little different.
My actual goal is to know if possible on client side when the PDF production operation is complete to hide the image.
Maybe the general approach is wrong?
aspx file
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager runat="server" EnableCdn="true"> </asp:ScriptManager>
<asp:UpdateProgress ID="UpdateProgress1" DynamicLayout="true" runat="server" AssociatedUpdatePanelID="updateGrid" DisplayAfter="0" >
<ProgressTemplate> <div class="progress"> <img src="../images/ajax-loader.gif" /> Waiting...</div> </ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="updateGrid" runat="server">
<ContentTemplate>
<asp:TextBox class='form-control' ID="txtMat" runat="server" style='width:110px' Text="1672"></asp:TextBox>
<asp:Button class='btn btn-primary' ID="cmdGO" runat="server" Text="Execute"/>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Panel ID="panelCMD" runat="server">
<asp:LinkButton ID="LinkButton3" OnClientClick="return postbackButtonClick();"
runat ="server" CssClass="btn btn-small btn-primary fullwidth" OnClick="mtdCreatePDF"><i class="icon icon-ok"></i> TEST PDF</asp:LinkButton>
</asp:Panel>
</ContentTemplate>
<Triggers >
<asp:PostBackTrigger ControlID="LinkButton3" />
</Triggers>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress2" ClientIDMode="Static" DynamicLayout="true" runat="server" AssociatedUpdatePanelID="UpdatePanel2" DisplayAfter="0" >
<ProgressTemplate>
<div class="progress">
<asp:image id="imgOld" runat="server" imageurl="../images/ajax-loader.gif" />
<br />
<img id="imgLike" src="../images/ajax-loader.gif" /> Attendere...</div>
</ProgressTemplate>
</asp:UpdateProgress>
</div>
</form>
<script src="Test.js" type="text/javascript"></script>
Test.js
function postbackButtonClick() {
updateProgress = $find("UpdateProgress2");
window.setTimeout(function () { updateProgress.set_visible(true); }, 100);
return true;
}
cs file
protected void mtdCreatePDF(object sender, EventArgs e)
{
byte[] content = null;
string TypeOutput = "RESPONSE";
string suffix = #"Pdf_PROD\Print.pdf";
string nameTGT = HttpContext.Current.Server.MapPath("~") + suffix;
var stream = new MemoryStream();
var writer = new PdfWriter(stream);
var pdf = new PdfDocument(writer);
var document = new Document(pdf);
document.Add(new Paragraph("Hello world!"));
document.Close();
if (TypeOutput == "RESPONSE")
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=print.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
//writer.SetCloseStream(false);
Response.BinaryWrite(stream.ToArray());
Response.End();
}
else
{
content = stream.ToArray();
using (FileStream fs = File.Create(nameTGT))
{
fs.Write(content, 0, (int)content.Length);
}
}
}
First, there needs to be a timeoutID for the timeout. We will use it later to disable the timeout. After pdf creation is completed, hideUpdateProgress() function will be called from code-behind to hide the progress image.
Test.js
var timeoutID;
function postbackButtonClick() {
updateProgress = $find("UpdateProgress2");
timeoutID = window.setTimeout(function () { updateProgress.set_visible(true); }, 100);
return true;
function hideUpdateProgress()
{
clearTimeout(timeoutID);
updateProgress = $find("UpdateProgress2");
updateProgress.set_visible(false);
}
To call hideUpdateProgress();, you can add this line at the end of mtdCreatePDF function.
ClientScript.RegisterStartupScript(Page.GetType(),
"hideUpdateProgress",
"hideUpdateProgress();",
true);
I solved it in the following way: I moved everything to the client side.
A. I added a client-side event on the click of the link button
<asp:LinkButton ID="LinkButton6" OnClientClick="return TestPDFDEF();" runat="server" CssClass="btn btn-small btn-primary fullwidth"><i class="icon icon-ok"></i> TEST PDF WebService Def</asp:LinkButton>
B. I added a WebMethod to the page that provides a variable of type [byte] to the Ajax call
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public byte[] GetPDF(List<Classes.GridCosts> MyGrid)
{
foreach (Classes.GridCosts rowsGrid in GrMyGridglia)
{
Console.Write(rowsGrid.Field1);
Console.Write(rowsGrid.Field2);
}
string suffix = #"Pdf_PRODOTTI\Print.pdf";
string nameTGT = HttpContext.Current.Server.MapPath("~") + suffix;
var stream = new MemoryStream();
var writer = new PdfWriter(stream);
var pdf = new PdfDocument(writer);
var document = new Document(pdf);
document.Add(new Paragraph("Hello world!"));
document.Close();
return stream.ToArray();
}
C. I have defined a class for receiving the grid that will be passed to the method
public class GridCosts
{
public string Field1{ get; set; }
public string Field2{ get; set; }
}
D. Added image that appears for hourglass:
$(document).ready(function () {
$('body').append('<div class="progress" id="ajaxBusy"><p><img src="../images/ajax-loader.gif"> Waiting..</p></div>');
$('#ajaxBusy').hide();
//$('#ajaxBusy').css({
// display: "none",
// left: "50%",
// margin: "0px",
// paddingLeft: "0px",
// paddingRight: "0px",
// paddingTop: "0px",
// paddingBottom: "0px",
// position: "fixed",
// right: "3px",
// top: "35%",
// width: "auto"
//});
// Ajax activity indicator bound to ajax start/stop document events
$(document).ajaxStart(function () {
$('#ajaxBusy').show();
}).ajaxStop(function () {
$('#ajaxBusy').hide();
});
});
E. I sent the variable referred to in point B to the user with Javascript
function TestPDFDEF() {
$(function () {
var MyGrid= new Array();
var CostsRow = {};
$('[id*=MyGrid]').find('tr:has(td)').each(function () {
CostsRow.Field1= $.trim($(this).find("td:nth-child(3)").text());
CostsRow.Field2= $.trim($(this).find("td:nth-child(4)").text());
MyGrid.push(CostsRow );
CostsRow = {};
});
type: "POST",
url: "WebService1.asmx/GetPDF",
contentType: "application/json; charset=utf-8",
data: '{MyGrid: ' + JSON.stringify(MyGrid) + '}',
dataType: "json",
beforeSend: function () {
},
success: function (data) {
data = data.d;
var byteArray = new Uint8Array(data);
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob([byteArray], { type: 'application/pdf' }));
a.download = 'FileName';
document.body.appendChild(a)
a.click();
document.body.removeChild(a)
},
complete: function (data) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
});
}

Send a script to the browser from C# back-end

I have an alert that I want to send the user only on his first entry to the website. The condition is in c# and that's the code I used. It doesn't send the alret. What should I do?
if ((string)Session["alert"] == null) {
Response.Write("<script type='text/javascript'>alert('WELCOME to the website!\nEnjoy!')</script>");
Session["alert"] = "done";
}
If you are using ASP.NET Web Forms u can use ScriptManager like this:
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('WELCOME to the website!\nEnjoy!')", true);
If you set the last parameter to true the content will get wrapped in script tags.
Your code would look like this:
if ((string)Session["alert"] == null) {
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('WELCOME to the website!\nEnjoy!')", true);
Session["alert"] = "done";
}
Try this code.
ASPX
<body>
<form id="form1" runat="server">
<asp:Literal id="ltrMessage" runat="Server"/>
</form>
</body>
ASPX.CS Code
if ((string)Session["alert"] == null) {
ltrMessage.Text="<script type='text/javascript'>alert('WELCOME to the website!\nEnjoy!')</script>";
Session["alert"] = "done";
}
To be considered, your literal item should be added to the end Body html tag.
I hope that helps.

modify alert message of script manager

Is there any way I can modify "alert('error !') part of the script manager to include message in the label below? I don't want to use the label for that, just display database error in the pop up window. I tried adding it with + but either it doesn't work or the pop up isnt displayed at all. Thanks
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('error !') ", true);
lblError.Text = "A database error has occured. <br /> <br />" +
"Message: " + ex.Message;
It doesnt like this:
<!-- all the links for datetime picker -->
<link rel="stylesheet" type="text/css" href="../style/jquery.datetimepicker.css"/ >
<script src="../Scripts/jquery.js"></script>
<script src="../Scripts/jquery.datetimepicker.js"></script>
<script>
$(function() {
$( "#datetimepicker" ).datetimepicker();
});
</script>
You can create a javascript function and call it to change the text of any label you want.
My suggestion is:
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", " changeLabel('" + ex.Message + "', '" + lblError.ClientID +"'); alert('error !'); ", true);
And the javascript function :
function changeLabel(text, id){
$("#"+id).val(text);
}
try
{
..
}
catch(Exception ex)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Database error ocurred : "+ ex.Message.ToString()+"')", true);
}
Unfortunately you cannot add HTML tag in javascript alert message.
Simple Alert
Make sure you strip out the single quote ' in ex.Message.
try
{
throw new Exception("test");
}
catch (Exception ex)
{
string message = string.Format("alert('A database error has occured. {0}');",
ex.Message.Replace("'", ""));
ScriptManager.RegisterStartupScript(this, this.GetType(),
"alert" + UniqueID, message, true);
}
jQuery Dialog
However you can use jQuery Dialog if you want to insert HTML.
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<div id="dialog" title="Basic dialog">
<div id="dialog-text"></div>
</div>
try
{
throw new Exception("This is an error message.");
}
catch (Exception ex)
{
string message = string.Concat("$(function () {$('#dialog').dialog(); " +
"$('#dialog-text').html('A database error has occured. " +
"<br /> <br />", ex.Message, "');});");
ScriptManager.RegisterStartupScript(this, this.GetType(),
"alert" + UniqueID, message, true);
}
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "<script language='javascript'>alert('A database error has occured.\n\n"+ ex.Message +"' );</script>", true);

fire javascript function from asp.net codebehind

This is my javascript function ,
function returnToParent() {
var oArg = new Object();
var oWnd = GetRadWindow();
oArg.ReturnValue = "Submit";
oWnd.close(oArg);
}
And this is how I call this function on client side
<button title="Submit" runat="server" id="close" onclick="returnToParent(); return false;">
OK</button>
I want to fire this function in server side button click event .
What I've done is add new button
<asp:Button runat="server" ID="rtxtSubmitChange" OnClick="rtxtSubmitChange_Click" Text="Submit" />
and in ButtonClick Event ,
protected void rtxtSubmitChange_Click(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(GetType(),
"MyKey",
"returnToParent();",
false);
}
But It doesn't work . What I am wrong in my code ?
Try
ScriptManager.RegisterStartupScript(this, this.GetType(), this.ClientID, "returnToParent()", true);
OR
ScriptManager.RegisterStartupScript(Page, Page.GetType(), this.ClientID, "returnToParent()", true);
For more details refer :ScriptManager.RegisterStartupScript Method

Using JavaScript if/then/else into ClientScript function

I am not so familiar with JavaScript, for that reason I need your help and advice! I have the following code in my asp button when is clicked. When the confirm box is displayed the user has two choices either to select OK or Cancel. The following code works in both of cases either OK or Cancel.
protected void cancel_Click(object sender, EventArgs e)
{
string url = "../../Default.aspx";
ClientScript.RegisterStartupScript(this.GetType(), "callfunction", "confirm('Data is not saved'); window.location.href = '" + url + "';", true);
}
However, what I am trying to do is to perform an if/then/else statement using JavaScript inside ClientScript function, and I don't know the correct syntax of that. e.g what I am trying to do
ClientScript.RegisterStartupScript(this.GetType(), "callfunction", "javascript:if(confirm('Data is not saved')== true) return {document.location.href = '../../Default.aspx'}; else {document.location.href = '../../Current.aspx'};", true);
Any advice would be appreciated!
Try the script before you add it server side, it easier to debug that way.
HereĀ“s two ways to write the if statement;
if (confirm('Data is not saved')) {
window.location.href = '../../Default.aspx';
} else {
window.location.href = '../../Current.aspx';
}
or even;
window.location.href = confirm('Data is not saved') ?
'../../Default.aspx' : '../../Current.aspx';
UPDATE
<asp:Button ID="cancel" runat="server" Text="Cancel" CausesValidation="false"
onClientClick="window.location.href = confirm('Data is not saved') ? '../../Default.aspx' : '../../Current.aspx';"
/>
Also note that you should rather use window.location than document.location.

Categories

Resources