2013-02-21 67 views
0

我正在使用Page.ClientScript.RegisterStartupScript();显示在asp.net C#在asp.net c#中不显示消息框使用Page.ClientScript.RegisterStartupScript()

消息如果我写了下面的代码,然后它的工作

Page.ClientScript.RegisterStartupScript(this.GetType(), "ShowMessage", string.Format("<script type='text/javascript'>alert('{0}')</script>", "Record Saved")); 
Page.ClientScript.RegisterStartupScript(this.GetType(), "Error", string.Format("<script type='text/javascript'>alert('{0}')</script>", ex.Message.ToString())); 

但如果我写

string Result = objChap.Insert(); 
Page.ClientScript.RegisterStartupScript(this.GetType(), "Error", string.Format("<script type='text/javascript'>alert('{0}')</script>", Result)); 

然后它不工作的手段,在没有消息框显示

我的完整代码是

protected void btnSave_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      objChap.FK_SemesterID = Convert.ToDecimal(drplstSem.SelectedValue); 
      objChap.FK_SubjectID = Convert.ToDecimal(drplstSub.SelectedValue); 
      objChap.ChapterName= txtChap.Text; 
      objChap.ChapterSName = txtChapShortName.Text; 
      objChap.Remarks = txtRemarks.Text; 
      objChap.Dta_User = Global.Dta_User; 
      objChap.Dta_Users = Global.Dta_User; 


      string Result = objChap.Insert(); 
      if (Result == "1") 
      { 

       Page.ClientScript.RegisterStartupScript(this.GetType(), "ShowMessage", string.Format("<script type='text/javascript'>alert('{0}')</script>", "Record Saved")); 

      } 
      else 
      { 
       Page.ClientScript.RegisterStartupScript(this.GetType(), "Error1", string.Format("<script type='text/javascript'>alert('{0}')</script>", Result)); 



      } 

     } 
     catch (Exception ex) 
     { 
      Page.ClientScript.RegisterStartupScript(this.GetType(), "Error", string.Format("<script type='text/javascript'>alert('{0}')</script>", ex.Message.ToString())); 
     } 
    } 
+0

我检查你的脚本 - 它的工作原理 – Alex 2013-02-21 10:19:13

+0

@voo但在我身边它不起作用 – Pritesh 2013-02-21 10:29:37

+0

也许这个字符串包含引号,打破了脚本。你能调试,看看'Result'的价值吗? – 2013-02-21 10:43:15

回答

3

当字符串包含单引号时,由于单引号也用于包装传递到alert()的值,所以会中断脚本。

为了克服这个问题,逃避引号:

Page.ClientScript.RegisterStartupScript(this.GetType(), "Error1", 
    string.Format("<script type='text/javascript'>alert('{0}')</script>", 
    Result.Replace("'", "\\'"))); 
+0

感谢它现在的作品 – Pritesh 2013-02-21 11:01:22

+0

我看不出这个答案后我的感受!我已经离开了我的代码成功执行的希望! 非常感谢。我希望我可以upvote它100次... – 2016-09-03 13:05:03

+0

@Am_I_Helpful大声笑,有时小事情很容易错过... :) – 2016-09-03 15:13:00

0

上述解决方案并没有为我工作,但我的情况只是略有不同。

这工作得很好:

Page.ClientScript.RegisterStartupScript(this.GetType(), "JSscript", "alert('this is a test');", true); 

这不:

String MetaJS = Convert.ToString(aList["JavaScript"].Value); //alert('this is a test'); 
Page.ClientScript.RegisterStartupScript(this.GetType(), "MetaScript", MetaJS, true); 

这并不:

String MetaJS = Convert.ToString(aList["JavaScript"].Value); //alert('this is a test'); 
Page.ClientScript.RegisterStartupScript(this.GetType(), "MetaScript", string.Format("{0}", MetaJS.Replace("'", "\\'")), true);