2012-08-27 77 views
0

我用一個簡單的asp.net應用條碼的工作,我需要在一些驗證是不正確的,顯示彈出消息。彈出警告消息asp.net

的事情是,我的消息是工作後,才按下「提交」按鈕兩次。第一次只是重新加載頁面,如果再次按下按鈕,彈出窗口就會出現!

編輯:我只是忘了添加一些細節。我使用的是VS 2010,使用C#構建Web Application 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,但這樣做使情況變得更糟。

謝謝!

+0

也許這可以幫助:http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/ValidatorCallout/ValidatorCallout.aspx –

+0

@AntonioBakula看起來像我需要的!謝謝。 – BrOSs

回答

2

嘗試更換此:

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(); 
} 

這將確保只將document is ready後會顯示你的消息,防止醜陋的格式問題。

+0

嘿,它的工作!只需添加使用System.Text;謝謝! – BrOSs

+0

不客氣。通過[達斯汀·迪亞茲]寫這個DOM就緒功能(http://dustindiaz.com/smallest-domready-ever)真的來手時,我不想整個jQuery庫添加到我的網頁只是爲了使用[jQuery的.ready()函數](http://api.jquery.com/ready/)。 –

3

的一種方法是,如果你的錯誤信息始終是相同的使用CustomValidator Class的ServerValidate事件。

如果沒有,使用這樣的事情:

Page.ClientScript.RegisterClientScriptBlock(typeof(Page), Guid.NewGuid().ToString(), "alert('my message')", true); 
+0

它總是一樣的錯誤。 – BrOSs

0

您指定的錯誤消息只說還不發生按鈕點擊事件,在頁面加載所以只有後,按鈕再次點擊你看到錯誤。

爲了做到這一點,你需要註冊頁面的腳本:

ClientScript.RegisterStartupScript(Page.GetType(), "SomeKey", "alert('Message Here');", true); 

http://msdn.microsoft.com/en-us/library/z9h4dk8y.aspx