How to Invoke Javascript Snippets Without Using RegisterClientScriptBlock
Sometimes you may need to integrate simple Javascript code blocks in your SharePoint custom application pages (or any ASP.NET page). In some cases, you may need to invoke this code block only when a specific condition is met. This can pose a challenge because the validation code will probably sit in your code behind (C#), but the client side script is in Javascript.
The first thing you may try is using the RegisterClientScriptBlock. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <script runat="server"> protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { try { SPWeb web = SPContext.Current.Web; ClientScript.RegisterClientScriptBlock(this.GetType(), "script", "<script language='javascript'> alert('hello'); </script>"); } catch (Exception ex) { Response.Write(ex.StackTrace.ToString()); } } } </script> |
You will still see a lot of posts that use this. However if you have tried the RegisterClientScriptBlock route in your application pages, and you get the following error:
Only Content controls are allowed directly in a content page that contains Content controls.
Enter the asp:Literal
An easy way to use simple Javascript blocks – sans the hassle of using the RegisterClientScriptBlock – is to use an asp:Literal control.
Step 1: Add an asp:literal control in your page content
1 2 3 4 5 6 7 8 9 10 11 | <asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server"> <asp:DropDownList ID="ddlCustomList" runat="server" OnSelectedIndexChanged="ddlCustomList_SelectedIndexChanged" AutoPostBack="true" Width="200px"> </asp:DropDownList> <script type="text/javascript" language="javascript"> <asp:Literal runat="server" ID="litSimpleJS"></asp:Literal> </script> </asp:Content> |
Step 2: Create the ASP.NET method or functionality that will set the Javascript values for your literal control
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | // in this method we want to check if the index in the // dropdown has changed, and depending on the condition, // an alert will be displayed private void ddlCustomList_SelectedIndexChanged(object sender, EventArgs e) { // reset the value of the literal to blank // otherwise the alert will always fire off this.litSimpleJS.Text = ""; if ( CheckIfAwesome() && (this.ddlCustomList.SelectedValue == "BLACKNINJA") ) { this.litSimpleJS.Text = "alert('Way to Go! " + "You are a Certified Black Ninja!' )"; } } |
There you go, simple but hassle free way of embedding Javascript to your ASP.NET pages.