With this code I show JavaScript alert message box in ASP.Net from server side using C#.
But I need show the message only on first access to the web page, how to do resolve this ?
Please help me.
My code below, thank you in advance.
protected void Page_Load(object sender, EventArgs e)
{
string message = "Hello!";
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());
}
You need to check that the page is not posting back before you display your alert:
if (!IsPostBack)
{
string message = "Hello!";
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());
}
Updates:
You can create a cookie to track the alert so it does not display after displaying during the initial page load:
private bool Alerted()
{
if (Request.Cookies["alerted"] != null)
return Server.HtmlEncode(Request.Cookies["alerted"].Value) == "true";
else
{
Response.Cookies["alerted"].Value = "true";
Response.Cookies["alerted"].Expires = DateTime.Now.AddDays(10);
return false;
}
}
Usage:
if(!Alerted())
{
// alert script here
}
Related
I have a Webview In that I am giving Some Instructions Page on webview page loading finished
This is my sample code
public void onPageFinished(WebView view, String url) {
if (!getSharedPreferences("MainA_SP", MODE_PRIVATE)
.getBoolean("checkbox", false)) {
AlertDialog.Builder adb=new AlertDialog.Builder(MainA.this);
LayoutInflater adbInflater = LayoutInflater.from(MainA.this);
View eulaLayout = adbInflater.inflate(R.layout.instpopup, null);
chkbx = (CheckBox)eulaLayout.findViewById(R.id.skip);
adb.setView(eulaLayout);
adb.setTitle("Welcome To Sample Page");
adb.setMessage(Html.fromHtml("App Instructions ....."));
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String checkBoxResult = "NOT checked";
if (chkbx.isChecked()) checkBoxResult = "checked";
SharedPreferences settings = getSharedPreferences(MainA_SP, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("skipMessage", checkBoxResult);
// Commit the edits!
editor.commit();
return;
} });
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String checkBoxResult = "NOT checked";
if (chkbx.isChecked()) checkBoxResult = "checked";
SharedPreferences settings = getSharedPreferences(MainA_SP, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("skipMessage", checkBoxResult);
// Commit the edits!
editor.commit();
return;
} });
SharedPreferences settings = getSharedPreferences(MainA_SP, 0);
String skipMessage = settings.getString("skipMessage", "NOT checked");
if (!skipMessage.equalsIgnoreCase("checked") ) adb.show();
}
try{
if (progressBar.isShowing()) {
progressBar.dismiss();
.
.
.
.
}
}catch(Exception exception){
exception.printStackTrace();
}
}
So Here Its working fine with Checkbox and sharedprefs
But the Problem Is that I have Given this alert in on page loading finished
So I am getting Alert multiple Times for a single url single page
I need to click the alert Every time I opens the App ... If I tick the Checkbox its not showing But For first run Alert is Showing Multiple Times
Update
I want to Show Alert on Page finished loading successfully
If you want to show alert at once after finished so you can use boolean value to check whether it is visible or not like below example.
private boolean alertVisiblity = false;
onPageFinished(){
//show your alert here
if(!alertVisiblity){
alertVisiblity = true;
new AlertDialog.Builder(MainActivity.this)
.setCancelable(false)
.setTitle("Alert")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
alertVisiblity = false; //or if you want to show it once never make it false or you can make it false before next call
}
}).show();
}
I have a 2 drop down lists with company name and company addresses and a remove button linked to a stored procedure. Addresses is not being refreshed even though I am calling databind() on that address drop down List. Can anyone point me out in the right direction?
//Button to remove Company
protected void btnremovecompany_2(object sender, EventArgs e)
{
if (ddlcompanyaddress2.SelectedIndex != 0) /*checked to see if an address is Selected first*/
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")/* if yes is clicked then procedd to deactivate that company address*/
{
String strConnString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "usp_update_company_active";
cmd.Parameters.Add("#companyname", SqlDbType.VarChar).Value = ddlcompany2.SelectedItem.Text.Trim();
cmd.Parameters.Add("#address", SqlDbType.VarChar).Value = ddlcompanyaddress2.SelectedItem.Text.Trim();
cmd.Parameters.Add("#category", SqlDbType.VarChar).Value = ddlTrades2.SelectedItem.Text.Trim();
cmd.Connection = con;
**ddlcompanyaddress2.DataBind();**
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
/*Display message saying company is deactivated*/
string message = "Company has been removed";
string script = "window.onload = function(){ alert('";
script += message;
script += "')};";
ClientScript.RegisterStartupScript(this.GetType(), "SuccessMessage", script, true);
con.Close();
con.Dispose();
}
}
else
{
/*if canceled is clicked then display no changes*/
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('No Changes were made!')", true);
}
}
else
{
string message = "Please pick an address first.";
string script = "window.onload = function(){ alert('";
script += message;
script += "')};";
ClientScript.RegisterStartupScript(this.GetType(), "SuccessMessage", script, true);
}
}
You might be missing the datasource for your dropdown list. I am unable to find datasource in your code. You have just called databind method.
Can you please bind the datasource?
added this code to the try{} area and it resets all the dropdowns with fresh data.
ddlgettrades2();
getcompany2(ddlTrades2.SelectedItem.Text);
getaddress2(ddlcompany2.SelectedItem.Text);
I am tring send data to another website's form from my 'Web Form' and submit it. But I couldn't achive it so far. I tried add id's bodyContent_ tag but still no progress. Can you detect where I am doing it wrong ? Thank You
protected void btnSend_Click(object sender, System.EventArgs e)
{
Response.Write(PostForm().ToString());
this.PostScript(Page);
}
public string PostForm()
{
string PostUrl = "http://www.teknobilsoft.com/Contact.aspx";
string Method = "post";
string name = "John";
string email = "john#doe.com";
string subject = "Mesaj";
string message = "some messages";
StringBuilder ppForm = new StringBuilder();
ppForm.AppendFormat("<form id='form1' action='{0}' method='{1}'>", PostUrl, Method);
ppForm.AppendFormat("<input id='txtName' value='{0}'>", name);
ppForm.AppendFormat("<input id='txtEmail' value='{0}'>", email);
ppForm.AppendFormat("<input id='ddlSubject' value='{0}'>", subject);
ppForm.AppendFormat("<textarea id='txtMessage' value='{0}'></textarea>", message);
ppForm.Append("</form>");
return ppForm.ToString();
}
private void PostScript(System.Web.UI.Page Page)
{
StringBuilder strScript = new StringBuilder();
strScript.Append("<script language='javascript'>");
strScript.Append("var ctlForm = document.getElementById('form1');");
strScript.Append("ctlForm.submit();");
strScript.Append("</script>");
ClientScript.RegisterClientScriptBlock(this.GetType(), "btnSendMessage", strScript.ToString());
}
What's the error message do you get?
Also, is there a reason why you use JavaScript to post the data? You can post using HttpWebRequest in C#:
http://www.stickler.de/information/code-snippets/httpwebrequest-post-data.aspx
I have set dropdown enable set to false in one button click and i will set enable="true" is not working in page load
here is my aspx
<asp:DropDownList ID="ddlJournal" runat="server" OnSelectedIndexChanged="ddlJournal_SelectionChanged" AutoPostBack="true" CssClass="drop" />
Here is my click event:
protected void btnTemplate_click(object sender, EventArgs e)
{
check.Value = "1";
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "Load_functions()", true);
//txtAddJournal.Attributes.Add("Style", "display:block");
//btnUpload.Attributes.Add("Style", "display:block");
//if (fileuploader.HasFile)
//{
try
{
string Filename = Path.GetFileName(fileuploader.FileName);
//fileuploader.SaveAs(Server.MapPath("~/") + Filename);
// fileuploader.SaveAs(Server.MapPath("D:\\Req Sep16\\") + Filename);
OleDbConnection myconnectionini = default(OleDbConnection);
OleDbDataAdapter mycommandini = default(OleDbDataAdapter);
//if (fileuploader.PostedFile.FileName.EndsWith(".xls") == false & fileuploader.PostedFile.FileName.EndsWith(".xlsx") == false)
//{
// // lbl_Error.Text = "Upload only excel format";
// Response.Write(#"<script language='javascript'>alert('Upload only excel format');</script>");
// return;
//}
//else
//{
gvDetails.DataSource = null;
string pathToSave = HttpContext.Current.Server.MapPath("~/UploadFiles/") + "Copy of Database_HBM";
//fileuploader.PostedFile.SaveAs(pathToSave);
//strFilePath = "D:\\Files\\" + fileuploader.FileName;
string constrini = "provider=Microsoft.Jet.OLEDB.4.0;data source=" + pathToSave + ";Extended Properties=Excel 8.0;";
DataSet ds = new DataSet();
// DataTable dt = new DataTable();
myconnectionini = new OleDbConnection(constrini);
mycommandini = new OleDbDataAdapter("select * from [Sheet1$]", myconnectionini);
ds = new DataSet();
mycommandini.Fill(ds);
gvDetails.DataSource = ds.Tables[0];
gvDetails.DataBind();
ddlJournal.SelectedIndex = -1;
ddlJournal.Enabled = false;
//ddlJournal.Attributes.Add("disabled", "disabled");
//}
}
catch (Exception ex)
{
string msg = ex.Message;
}
//}
}
And my page load event is
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Grid", "headerLock();", true);
// ScriptManager.RegisterStartupScript(Page, this.GetType(), "Key", "<script>headerLock();</script>", true );
if (!IsPostBack)
{
Bindddl();
BindGrid(null);
ddlJournal.Enabled = true;
}
else
{
ddlJournal.Enabled = true;
}
}
button :
<asp:Button ID="btnUpload" runat="server" Text="Template 1" OnClientClick="return Validate();"
OnClick="btnTemplate_click" CssClass="btn" />
but still my dropdown list is disable.
suggest me get a solution
thanks in advance
You can set dropdown list Enabled false from its control only like this
<asp:DropDownList ID="ddlJournal" runat="server" OnSelectedIndexChanged="ddlJournal_SelectionChanged" AutoPostBack="true" CssClass="drop" Enabled="false"/>
And the rest code should work fine.
Please mark it helps
Understand that your if-else condition in Page_Load() method is the main culprit. You're always setting ddlJournal.Enabled = true, no matter what. Seems like you didn't properly understand the concept of IsPostBack. ddlJournal is supposed to be disabled when IsPostBack is true, because that's what you want. Otherwise, it's supposed be enabled.
This is a very concise explanation about what IsPostBack is:
Postback in an event that is triggered when a action is performed by a contol on a asp.net page. for eg. when you click on a button the data on the page is posted back to the server for processing.IsPostback is normally used on page _load event to detect if the page is getting generated due to postback requested by a control on the page or if the page is getting loaded for the first time.
[a comment from http://forums.asp.net/t/1115866.aspx?What+is+IsPostBack ]
So based on that, you should change your code like the following:
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Grid", "headerLock();", true);
if (!IsPostBack)
{
//When IsPostBack is false, ddlJournal should be enabled
Bindddl();
BindGrid(null);
ddlJournal.Enabled = true;
}
else
{
//Else, IsPostBack is true, so, ddlJournal should be disabled
ddlJournal.Enabled = false;
}
}
Also, you don't need this in your btnTemplate_click() method since you're doing this on page load:
ddlJournal.Enabled = false;
protected void Button1_Click(object sender, EventArgs e)
{
if (count > 100)
{
StringBuilder javascript = new StringBuilder();
javascript.Append(" <script language=\"javascript\" type=\"text/javascript\">");
javascript.Append(" var tmp = confirm(\"No:Of Records exceeds 1000.Please confirm you want to continue\");");
javascript.Append("if (tmp)");
javascript.Append("{document.getElementById(\" <%=TextBox1.ClientID%>\").value=\"1\"; alert(document.getElementById(\"<%=TextBox1.ClientID %>\").value);}");
javascript.Append(" </script>");
ClientScript.RegisterStartupScript(GetType(), "recordscript", javascript.ToString(), false);
return;
}
}
Here I want to set the value of the textbox by clicking the button event and oly that condition is true.So I cant call that function from source.actually that function gets called but the textbox value doesnt set..I really dont understand where is the problem..
protected void Button1_Click(object sender, EventArgs e)
{
if(count>100)
{
StringBuilder javascript = new StringBuilder();
javascript.Append(" <script language=\"javascript\" type=\"text/javascript\">");
javascript.Append(" var tmp = confirm(\"No:Of Records exceeds 1000.Please confirm you want to continue\");");
javascript.Append("if (tmp)");
javascript.Append("{document.getElementById('" + TextBox1.ClientID + "').value=\"1\"; alert(document.getElementById('" + TextBox1.ClientID+ "').value);}");
javascript.Append(" </script>");
ClientScript.RegisterStartupScript(GetType(), "recordscript", javascript.ToString(), false);
return;
}
}
}
You need to concatenate the TextBox1.ClientID with your javascript string. The code you have will get rendered to the page as is, look at the output of your rendered page with view source, you will see the string '<%= TextBox1.ClientID =%>' not the expected ID. Keep in mind that the inline display expression <%= =%> is equivalent to a server Response.Write().