ASP.Net C# Format Javascript Delete Confirmation Alert Containing Apostrophes

How to format a javascript delete confirmation alert with text containing apostrophes.

ASP.Net Button with OnClientClick

<asp:Button ID="Delete" runat="server" Text="Delete" OnClick="Delete_Function" OnClientClick='<%# FormatDeleteAlert() %>' CssClass="buttonText" />

Javascript Alert Function

protected string FormatDeleteAlert()
{
  string lineitem = "";
  lineitem = Eval("ItemName").ToString().Replace("'", "\\'");
  StringBuilder sConfirm = new StringBuilder();
  sConfirm.Append("return confirm('Are you sure you want to delete " + lineitem + "?');");
  return sConfirm.ToString();
}
Advertisements

Adding JavaScript to Execute on SharePoint Page’s Body Onload Event

The SharePoint master page contains the <body> element.

SharePoint provides the “_spBodyOnLoadFunctionNames” array.

When the SharePoint page’s body is loaded, the onload event handler executes each function whose name is contained in this array.

You can add “ MyFunctionName” to the array and it will run when the body’s onload event fires.

<script language="javascript">
_spBodyOnLoadFunctionNames.push("MyFunctionName");
function MyFunctionName()
 {
 // Code
 }
 </script>

http://blogs.msdn.com/b/sharepointdesigner/archive/2007/06/13/using-javascript-to-manipulate-a-list-form-field.aspx