[英]popup alert message asp.net
我正在使用一個簡單的asp.net條碼應用程序,當某些驗證不正確時,我需要顯示一條彈出消息。
問題是,只有按兩次“提交”按鈕后,我的消息才起作用。 第一次只是重新加載頁面,如果我再次按下按鈕,就會彈出窗口!
編輯:我只是忘記添加一些細節。 我正在使用VS 2010,使用C#作為背后的代碼構建Web應用程序asp.net。
public partial class Barcode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
Validate();
if (IsValid)
//
{
string kemet = kemetTextBox.Text;
string sud = sudTextBox.Text;
if (kemet.Length == 14 && sud.Length == 28) // SOME VALIDATION CONTROL
{
if (kemet.Substring(1) == sud.Substring(0, 13) && kemet != "" && sud != "")
{
//resultLabel.Text = "HIGH VOLUME<br/>";
redImage.Visible = false;
greenImage.Visible = true;
}
if (kemet.Substring(1) != sud.Substring(0, 13) && kemet != null && sud != null)
{
// resultLabel.Text = "LOW VOLUME<br/>" + kemetEd + sudEd;
greenImage.Visible = false;
redImage.Visible = true;
}
}
else
Button1.Attributes.Add("onClick", "javascript:alert('Message Here');"); // HERE WOULD BE THE ERROR MSG
我嘗試將IsPostBack設置為false,但這會使情況更糟。
謝謝!
如果您的錯誤消息始終相同,則一種方法是使用CustomValidator類 ServerValidate事件。
如果沒有,請使用以下方法:
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), Guid.NewGuid().ToString(), "alert('my message')", true);
嘗試替換此:
Button1.Attributes.Add("onClick", "javascript:alert('Message Here');");
這樣:
RegisterDOMReadyScript("alert message", "alert('Message Here');");
使用以下輔助方法:
public void RegisterDOMReadyScript(string key, string script)
{
string enclosed = EncloseOnDOMReadyEvent(script);
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), key, enclosed, true);
}
private string EncloseOnDOMReadyEvent(string str)
{
StringBuilder sb = new StringBuilder();
sb.Append("function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()} r(function(){")
.Append(str)
.Append("});");
return sb.ToString();
}
這樣可以確保僅在文檔准備好后才顯示您的消息,從而避免出現難看的格式問題。
您僅將錯誤消息分配給尚未發生的按鈕單擊事件,因此只有在頁面加載並再次單擊按鈕之后,您才會看到錯誤。
為此,您需要在頁面中注冊腳本:
ClientScript.RegisterStartupScript(Page.GetType(), "SomeKey", "alert('Message Here');", true);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.