0

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

如果我写下面的代码,那么它的工作

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

2 回答 2

4

当字符串包含单引号时,它会破坏脚本,因为单引号也用于包装传递给的值alert()

要克服这个问题,请转义引号:

Page.ClientScript.RegisterStartupScript(this.GetType(), "Error1", 
    string.Format("<script type='text/javascript'>alert('{0}')</script>", 
    Result.Replace("'", "\\'")));
于 2013-02-21T10:56:16.213 回答
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);
于 2014-07-31T16:17:30.063 回答