I want to bring up a js alert box on asp.net button click. The code i have is
String jscript = @"<script language = 'javascript'> alert('This is my title');</script>";
ClientScript.RegisterStartupScript(GetType(), "_jscript", jscript);
it works fine, but I want to have some more js popups later for some validation, where I assume I have to write the same code, but unfortunately it does not load rest of the popups on the same page.
Is this to do with update panels?
The control I am validating is
if (dp_menu.SelectedIndex > 0)
{
//continue program
}
else
{
//show popup
//this pop p doesn't show up at all?
String jscript = @"<script language = 'javascript'> alert('Another popup');</script>";
ClientScript.RegisterStartupScript(GetType(), "_jscript", jscript);
}
Take a look at the specification for RegisterStartupScript
, specifically the Remarks section:
A client script is uniquely identified by its key and its type. Scripts with the same key and type are considered duplicates. Only one script with a given type and key pair can be registered with the page. Attempting to register a script that is already registered does not create a duplicate of the script.
If you're passing in the same type via GetType()
and the same key, "_jscript"
, every time, then only the first call will result in any <script>
being rendered. This is by design.
Poor Fix : Replace your unchanging key "_jscript"
with a different key for each validation you perform, eg "_valNameIsBlank"
, "_valNoItemSpecified"
.
Better Fix : Avoid annoying your users with multiple validation popups by:
List<string>
of all your validation failures i would give you some thing more effective,
costume control
add this class to library
using System.Text;
using System.Web.UI;
using System.ComponentModel;
namespace ClientSide
{
[DefaultProperty("Text"),
ToolboxData("<{0}:MessageBox runat=server>"
+ "</{0}:MessageBox>")]
public class MessageBox : System.Web.UI.Control
{
private string text="";
[Bindable(true),
Category("Appearance"),
DefaultValue("")]
public string Text
{
get {return text;}
set {text = value;}
}
protected override void Render(HtmlTextWriter output)
{
if (text.Length>0)
{
StringBuilder sb = new StringBuilder();
sb.Append("<script language='javascript'>");
sb.Append("alert('"+text+"')");
sb.Append("</script>");
output.Write(sb.ToString());
}
}
}
}
to use it you have to register the control in the top of aspx page
<%@ Register TagPrefix="cc1" Namespace="ClientSide" Assembly="Library_Name" %>
3- then you can use it like this way in the aspx page
<cc1:MessageBox id="MessageBox1" runat="server" Text="popup Message"></cc1:MessageBox>
In RegisterStartupScript Keyvalues should be different for each script
Try different KeyValues instead of using "_jscript" in all script.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.