I am new in development, I want to show the alert message on button click after that I want to redirect the on another page. my button code is like below:
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
Response.Write("<script type='text/javascript'> alert('Please wait for approval!');</script>");
Response.Redirect("~/profile/scrapbook.aspx?uid=" + Request.QueryString["uid"], false);
}
in this case alert is not working, If I remove the Response.Redirect then it will works properly.
Please suggest me how to call he alert message after that redirect on another page.
You are mixing server side and client side code.
The Response.Redirect("~/profile/scrapbook.aspx?uid= is server side and the Alert won't wait the action of the user to execute it...
What you will need is to do you redirect in Javascript or to use something else than an Alert for the message.
Solution 1
You display a Alert message in Javascript (client side) when the user press okay you do a redirect in Javascript.
Solution 2
You display a message in the HTML with a button in ASP with an event that will do a call to the server and redirect your user to the page you desire.
Add your script like this:
const string scriptString = "<script type='text/javascript'> alert('Your friend request sent to the user! Please wait for approval!');</script>";
ClientScriptManager script = Page.ClientScript;
script.RegisterClientScriptBlock(GetType(), "randomName", scriptString);
Do not use Response.Write to render your JavaScript. Use RegisterClientScriptBlock or RegisterStartupScript instead.
Your example should be using RegisterStartupScript, since it's rendering executing script, and not function declarations.
Related
Using insert functionality of an aspx DetailsView. Would like to show a javascript modal popup window while the new record is processed and added to the database. I can hook the button click in DetailsView_ItemCommand. It's not working, so I started trying to figure out whats going on by simply displaying a javascript Alert() popup. But can't get that to even work. Here's the relevant DetailsView_ItemCommand:
protected void DetailsViewInsertFPL_ItemCommand(object sender, DetailsViewCommandEventArgs e)
{
if (e.CommandName == "Insert")
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "waitMessage", "alert('Please wait while your request is processed');", true);
return;
}
}
After the record is inserted, there is a redirect to another aspx page.
Can anyone steer me down the right path? I'll be looking at some of the aspx page and DetailsView properties next to see if something there isn't set correct.
You cant just use
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "waitMessage", "alert('Please wait while your request is processed');", true);
then preceeded by a
response.redirect("toanotherpage.aspx");
ScriptManager.RegisterStartupScript will render your script after all the elements in the page (right before the form's end tag) hence not executing it when you use response redirect on the same code block.
To achieve what you want you could do one of the following solutions,
Create a Javascript and place you the redirect or for this instance
window.location there after the Alert message you want
Create a pop-up modal using other methods like bootstrap, on the modal declare a button with a code for response.redirect.
Alex Kudryashev's suggestion to enclose the DetailView within an asp:UpdatePanel and use the asp:UpdateProgress to show the "please wait while your request is processed" gave me the solution I needed in this case.
Infrequent user here, so not sure how to give the points to Alex as his suggestion was a comment rather than an answer. Feel free to let me know how to handle the votes in that case.
Thanks!!!! I've been banging my head against the wall for a couple of days to get this one working.
currently I am facing a problem with pop up msgs.
The messages should prompt out first time click on a NEXT button.
when we go to the next pages and back to the previous pages, and click on the same NEXT button, the pop up msgs should not appear.
how can i fix this?
This is button code
<asp:Button ID="Button1" runat="server" onclick="Button1_Click1" Text="Next" Width="100px" />
This is the function() for my clickedOnce
<script type="text/javascript">
window.document.onload = function()
{
var clickedOnce = false;
Button1.Button1_Click1 = function ()
{
if(!confirm('Please make sure the employee particulars and reporting line details are correct before save. \nClick OK to save and continue if all details are correct.\nClick Cancel and contact HR Admin if details appear is not up to date.'))return false;
clickedOnce = true;
}
}
</script>
Thank you. your kindness and help much appreciated.
Well, since you only want to run it once, could you give the user a cookie that lasts until the browsing session is over when they fist click the button? If they have the cookie, then you could skip over the line of code that you only want to run once.
Your code doesn't work at all. The main issue is how you try to catch click event.
<asp:Button ID="Button1" runat="server" onclick="Button1_Click1" Text="Next" />
It means that Button1_Click1 function runs at server. No client-side event occurs. To do something on client side you have to add onclientclick="someFunction()" to your button declaration.
OK, you add this. Now go to javascript.
function someFunction(){
var clickOnce = getCookie('clickOnce');
//Look #Darkrifts comment (link) how to do it.
//Just in case I reproduce the link http://www.w3schools.com/js/js_cookies.asp
if(!clickOnce || confirm('blah blah')){
document.cookie = 'clickOnce=1';
//no need to return anything
}
//if a visitor doesn't click "ok" then the popup appear again
}
It is also possible to set Session["clickOnce"] = true; on server side and use it from Page_Load server side handler but it may not work if a visitor return to the page using browser Back button.
protected void Button1_Click1(object sender, EventArgs e){
Session["clickOnce"] = true;
//more code
}
protected void Page_Load(object sender, EventArgs e){
if(Session["clickOnce"] != true)
Button1.OnClientClick = "someFunction()";
else
Button1.OnClientClick = "";
//more code
}
This can be achieved in multiple ways. You need to select the most efficient approach for your need. First of all you need to understand the ASP.Net page life cycle, persisting information between pages and ViewState.
In a nutshell...
Whenever your page reloads all elements (including JavaScript variables, be it global or local variables) in your page get's initialised. And then a feature in ASP.Net comes into play. I.e. ViewState. If this is set to true in page level or for each control it'll persist information of the controls in the page (depends on how you set this). But, this is page specific.
And, you could persist information between pages using following approaches
Query string
Session variables
Cache
Form posts
Cookies
Data store (e.g. text, xml or any other database/ data store)
Before you use any of the above mentioned approaches you must think about your requirement. #Alex Kudryashev came up with a good example while I was writing this answer. Let me know if you need example with a different approach or any clarifications.
I have a button and textbox on my page aspx and on button click event I am displaying alert message.
Now when I run website and click on button it display message but after that when I press F5 (Refresh) it again display message. So my question how to remove message when I click F5.
Below is my code for button click:
protected void btnExport_Click(object sender, EventArgs e)
{
DisplayMessage("There is no data to Export.", this);
}
and
public void DisplayMessage(String strMessage, Control name)
{
string script = "<script language='javascript'>alert('" + strMessage + "');</script>";
ScriptManager.RegisterStartupScript(name, name.GetType(), "JSCR", script, false);
}
Change your script as follows
string script = "alert('hello');window.location.href='Default.aspx'";
where i assumed Default.aspx is your page
You are instigating a client side event from server side which usually does not make sense.
The behaviour you are noticing is correct, when you clicked that button a request is posted to the server which calls your button click handler which then registers the client side script when the response is returned. When you press F5 to refresh your browsers is posting that exact same request again to the server, so the button handler is fired again.
I advise you read a little about how Post And Gets
work as well as how postbacks work in ASP.
I need to display a modal popup from a aspx.cs page. I need to invoke the popup from server side because before the popup opens, I need to pass an ID into the popup via query string.
this is my code to display the popup.
protected void btnNote_Click(object sender, EventArgs e)
{
string queryStringParam = "some text"; // some server code here to get the string ready;
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "openNotePopup('"+ queryStringParam +"');", true);
}
And this is the javascript to get the parameter and launch the modal popup.
function openNotePopup(var param)
{
var noteResult = window.showModalDialog("AddEditNote.aspx?Note=" + param, "Add/Edit Notes", 'center:yes; dialogWidth:600px; dialogHeight:500px;');
document.getElementById("hidden_NoteText").value = noteResult;
}
When the popup is closed, I pass a string value as window.returnValue which is captured in the noteResult variable in client side.
Now I need to capture the popup close event in my server side. I can capture the event in client side but I need the event in server side so that I can pick up the value from the hidden field and process it.
How can I achieve this?
I found a thread that seems to tackle this very issue. Hopefully this is something similar to what you were looking for:
Javascript confirm message problem
I suggest you to write you own function on ShowDialog like this:
showNotePopup('NotePopup', title, closeNotePopup);
NotePopup - id of your popup;
showNotePopup should describe what you wanna see in your popup, how it will close;
closeNotePopup function you bind to popup closing and inside it you can make for example post-request and this way you'll catch on server when your popup is closing.
I am doing web development.
I have a page to do with credit card, which when user click "refresh" or "Back", the transaction will be performed one more time, which is unwanted.
This include Browser top left "Back" & "Refresh" button, "right click->Refresh/Back", press "F5" key.
This is to be done on certain cgi page only, not all of them.
Can this be done using Javascript? Or any other method?
The standard way is to do it in 3 steps.
the form page submits fields to processing page
processing page processes data and redirects to result page
result page just displays results, reloading it won't do any harm.
This breaks the basic browser user experience model...users should always be able to use the Refresh and Back buttons in their browser. Recommend that you fix your page another way.
If you update your question to include the server language/platform/technology that you are using then someone might be able to suggest a solution.
The simple fact that resubmitting the form generates a duplicate transaction is worrying. You should have some sort of check to ensure each submit of form data is unique.
For example, the page which would submit the form should be given a unique ID that gets submitted with the form. The business logic should then be able to recognise that the form submitted has already been processed (as the (no longer) unique ID will be the same), so ignores the second attempt.
The 'standard way' still doesn't stop clients from clicking the back button twice... or even going back and resubmitting the form if they don't think (for whatever reason) it has been processed.
generate a random string and store it in session,
then output it to your form as a hidden value,
check the submitted and store variable, if matches process your request,
go to 1.
Place this code on the form page
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now-new TimeSpan(1,0,0));
Response.Cache.SetLastModified(DateTime.Now);
Response.Cache.SetAllowResponseInBrowserHistory(false);
You shouldn't try to "block" these actions.
What you should do is make sure that nothing happends when someone "double submits" the form.
and in some browser you canĀ“t even do that, and this is good!
The best way is to have enough session handling logic that you can recognise the 2nd (and onwards) attempt as "this is just a re-submission" and ignore it.
I didn't see this here so here it is.
Put a unique token in the form.
The submit button triggers an xmlhttp(ajax) request to the server to create a session variable named after the token with a stored value of 1.
The ajax request submits the form after receiving a positive state change.
The form processing script checks for the session variable withe the stored value of 1.
The script removes the session variable and processes the form.
If the session variable is not found, the form will not be processed. Since the variable is removed as soon as its found, the form can only be run by pressing the submit button. Refresh and back will not submit the form. This will work without the use of a redirect.
vartec:s solution solves the reload-problem, not the back-problem, so here are a solution to that:
The form page sets a session variable, for example session("fromformpage")=1
The processing page check the session variable, if its ="1" then process data and redirect to result page if any other than ="1" then just redirect to result page.
The result page sets the session variable to "".
Then if the user is pressing back button, the processing page will not do the process again, only redirect to process page.
I found the above Post/Redirect/Get explanations a little ambiguous
Here's what I followed and hopefully it helps someone in the future
http://wordsideasandthings.blogspot.ca/2013/04/post-redirect-get-pattern-in-php.html
Essentially the process based on the above solution is:
Submit from the FORM page to the processing page (or to itself)
Handle database or payment processing etc
If required, store user feedback message in a session variable, possible error messages etc
Perform header redirect to results page (or to original form page). If required, display custom message from processing page. Such as "Error Credit Card payment was rejected", and reset session variables.
Redirect with something like:
header("HTTP/1.1 303 See Other");
header("Location: http://$_SERVER[HTTP_HOST]/yourfilehere.php");
die();
The header redirect will initiate a GET request on "yourfilehere.php", because a redirect is simply that, a "request" to fetch data FROM the server, NOT a POST which submits data TO the server. Thus, the redirect/GET prevents any further DB/payments processing occurring after a refresh. The 301 error status will help with back button pressing.
Helpful Reading:
http://en.wikipedia.org/wiki/URL_redirection#HTTP_status_codes_3xx
http://www.theserverside.com/news/1365146/Redirect-After-Post
http://wordsideasandthings.blogspot.ca/2013/04/post-redirect-get-pattern-in-php.html
https://en.wikipedia.org/wiki/HTTP#Request_methods
http://en.wikipedia.org/wiki/Post/Redirect/Get
Just put this javascript on the html section of aspx page above head section
<script type = "text/javascript" >
function disableBackButton()
{
window.history.forward();
}
setTimeout("disableBackButton()", 0);
</script>
We need to put it on the html section of the page which we want to prevent user to visit by hitting the back button
Complete code of the page looks like this
<%# Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script type = "text/javascript" >
function disableBackButton()
{
window.history.forward();
}
setTimeout("disableBackButton()", 0);
</script>
</head>
<body onload="disableBackButton()">
<form id="form1" runat="server">
<div>
This is First page <br />
<br />
Go to Second page
<br />
<br />
<asp:LinkButton ID="LinkButton1" runat="server"
PostBackUrl="~/Default2.aspx">Go to Second Page
</asp:LinkButton></div>
</form>
</body>
</html>
If you are using firefox then use instead of onload
If you want to disable back button using code behind of aspx page,than you need to write below mentioned code
C# code behind
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
string strDisAbleBackButton;
strDisAbleBackButton = "<script language="javascript">\n";
strDisAbleBackButton += "window.history.forward(1);\n";
strDisAbleBackButton += "\n</script>";
ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "clientScript", strDisAbleBackButton);
}
We can also achieve this by disabling browser caching or cache by writing this line of code either in Page_load event or in Page_Init event
protected void Page_Init(object Sender, EventArgs e)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
Response.Cache.SetNoStore();
}
Doing this,user will get the page has expired message when hitting back button of browser
Demo is :
This code works for not back from current page me..
Here I put a code which helps you , not open contextmenu and on browser reload ask you leave a page or not...
I am trying the ask click on browser back button
jQuery( document ).ready(function() {
document.onkeydown = fkey;
document.onkeypress = fkey
document.onkeyup = fkey;
var wasPressed = false;
function fkey(e){
e = e || window.event;
//alert(e.keyCode);
if( wasPressed ) return;
if (e.keyCode == 116 || e.keyCode == 8 || e.keyCode == 17) {
// alert("f5 pressed");
window.onbeforeunload = null;
return true;
}
}
window.onbeforeunload = function (event) {
var message = ''; // Type message here
if (typeof event == 'undefined') {
event = window.event;
}
if (event) {
event.returnValue = message;
}
return message;
};
jQuery(function () {
jQuery("a").click(function () {
window.onbeforeunload = null;
});
jQuery(".btn").click(function () {
window.onbeforeunload = null;
});
//Disable part of page
$(document).on("contextmenu",function(e){
return false;
});
});});
Thanks,