Pritesh Pritesh - 11 months ago 115
ASP.NET (C#) Question

Not showing message box in asp.net c# using Page.ClientScript.RegisterStartupScript()

I am using Page.ClientScript.RegisterStartupScript(); to show a message in asp.net C#

If i Write below code then its working

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


But if I write

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


then its not working means that messagebox in not displaying

My full code is

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

Answer Source

When the string contains single quotes, it breaks the script since single quotes are also used to wrap the value passed to alert().

To overcome this, escape the quotes:

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