Javascript confirm dialog coming up twice; Jumping back after clicking Element - javascript

Beginner here, so please be gentle.
I'm trying to ask the User for confirmation. When he accepts, my javascript invokes a Button to run some code behind. The code behind will run a JavaScript function which alerts, just so I can see if it all works. What happens is, that after my first confirm() dialog, a second dialog appears. After confirming again, the code runs and my second JavaScript function confirms by alerting. But after I press okay on that, the whole thing jumps back to my first function and I get into a loop!
ASPX:
<script type = "text/javascript">
function ConfirmComputerOverwrite(ComputerName) {
if (confirm("Overwrite present computer " + ComputerName + " ?"))
{
}
else
{
}
document.getElementById("Test").click()
}
function allworkedout()
{
alert("asdf");
}
Code behind:
public string ComputerName = "";
protected void Page_Load(object sender, EventArgs e)
{
string ComputerName = "Computer1";
this.ComputerName = ComputerName;
StringBuilder sb = new StringBuilder();
sb.Append("ConfirmComputerOverwrite('" + ComputerName + "');");
ScriptManager.RegisterStartupScript(this, GetType(), "ConfirmComputerOverwrite", sb.ToString(), true);
}
protected void Test_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
sb.Append("allworkedout();");
ScriptManager.RegisterStartupScript(this, GetType(), "allworkedoutID", sb.ToString(), true);
}
Thanks in advance !

Unless you are using ajax, the whole page is reloaded after click, so your javascript is executed again, prompting for confirmation, etc...

Related

Calling a JS function from an ASP.Net MasterPage

I have a requirement to read image data from SQL Server (company logo) and keep it in localStorage. This company logo is displayed in the master page left sidebar so that in every client page it will be visible.
I use 3 JS functions in the Master page for this purpose.
function storageCheck() {
if (localStorage.getItem("imgData") === null) //check availability
document.getElementById('<%=hdfStorage.ClientID %>').value = "true"; //assign true to a hidden field
else
document.getElementById('<%=hdfStorage.ClientID %>').value = "false";
}
function storelogo(imgData) { //store image data
localStorage.setItem("imgData", imgData);
}
function getImg() { //get data
var dataImage = localStorage.getItem('imgData');
document.getElementById('imgCompanyLogo').src = dataImage;
alert('got')
}
In the code behind of the Master page I am calling these JS functions
protected void Page_LoadComplete(object sender, EventArgs e)
{
if (!IsPostBack)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "checkfn", "storageCheck()", true);
if (hdfStorage.Value == "true")
ScriptManager.RegisterStartupScript(this, this.GetType(), "storelogoo", "storelogo('" + <Base64String img data from database> + "');", true);
else if (hdfStorage.Value == "false")
ScriptManager.RegisterStartupScript(this, this.GetType(), "getlogo", "getImg();", true);
}
}
I have tried putting it in the Page_Load event but no use. The issue I am facing is these functions are not getting called and if called from the Page Load event the hiddenfield control wont get the value when I check using hdfStorage.Value == "true"
I suggest to put it in memory as singleton or session, all people work like this

server side alert message that shows unwanted when get back and reload the page

I have a submit button and below is the code in the onClick event :
protected void btnSubmit_Click(object sender, EventArgs e)
{
...
ScriptManager.RegisterClientScriptBlock(this, GetType(), "alertMessage", "alert('Submitted')", true);
}
This code works.
But the problem is when user go to next page by this:
Response.Redirect("page2.aspx");
and when click backspace to get back to page1 and,
before the reload,
the following message box appears!!
this problem happened again when we refresh(F5) the page1 after submiting
how will I solve this?
I tried:
1. if(isPostback)// before the alert
2. string message = "Submitted";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload=function(){");
sb.Append("alert('");
sb.Append(message);
sb.Append("')};");
sb.Append("</script>");
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
In such case, you can implement a special code block to detect browser refresh as
private bool refreshState;
private bool isRefresh;
protected override void LoadViewState(object savedState)
{
object[] AllStates = (object[])savedState;
base.LoadViewState(AllStates[0]);
refreshState = bool.Parse(AllStates[1].ToString());
if (Session["ISREFRESH"] != null && Session["ISREFRESH"] != "")
isRefresh = (refreshState == (bool)Session["ISREFRESH"]);
}
protected override object SaveViewState()
{
Session["ISREFRESH"] = refreshState;
object[] AllStates = new object[3];
AllStates[0] = base.SaveViewState();
AllStates[1] = !(refreshState);
return AllStates;
}
In the button submit you can do it as
protected void btn3_Click(object sender, EventArgs e)
{
if (isRefresh == false)
{
Insert Code here
}
}

Get Javascript Variable Value in Server Side Without Page Load

I am trying to get value of Javascript variable
on server side, but it always shows values on
second button click and I don't want to reload this page again
protected void Button1_Click(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(Page.GetType(), "MessageBox", "<script language='javascript'>setValues();</script>");
Thread.Sleep(5000);
Response.Write(HiddenField1.Value);
}
Javascript Code . . . ..
<script type="text/javascript">
function setValues()
{
var abc = "thi is first";
document.getElementById('<%=HiddenField1.ClientID%>').value = abc;
}
</script>

New Windows focus issue JavaScript and C#

I have below code which I am using to open a new window up on buttonclick. I am executing below code in button click event : New windows opens up but it does not focus, it just goes behind the main page.... please how can I fix this issue....
protected void btnView_Click(object sender, EventArgs e)
{
int activeTab = pgSearchFrm.ActiveTabIndex;
string sel = this.ddlFields.SelectedValue;
string url = "\\ATPrintView.aspx?SearchID=" + Convert.ToString(activeTab) + "&Col=" + sel + "&Val=" + txtFields.Text;
ScriptManager.RegisterStartupScript(this, this.GetType(), "Open", "window.open('" + url + "','_blank','height=500,width=800,status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=no,titlebar=no').focus();", true);
}

javascript alert not firing

I have a new page with the following:
The Response.Redirect works, but I don't get a popup before hand...
Any ideas???
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["timeout"] != null && Request.QueryString["timeout"].ToString().Equals("yes"))
{
Response.Write("<script>alert('Your Session has Timedout due to Inactivity');</script>");
Response.Redirect("Default.aspx");
}
}
The Response.Redirect call never returns the code to the user. It immediately redirects the user to the next page. From the MSDN on Response.Redirect: "Any response body content such as displayed HTML text or Response.Write text in the page indicated by the original URL is ignored."
The Response.Redirect redirects the browser and your JavaScript does not get executed.
Try redirecting in JavaScript instead:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["timeout"] != null && Request.QueryString["timeout"].ToString().Equals("yes"))
{
Response.Write("<script>" +
"alert('Your Session has Timedout due to Inactivity');" +
"location.href='Default.aspx';" +
"</script>");
}
}

Categories