Last active
December 21, 2015 14:39
-
-
Save Termiux/6321596 to your computer and use it in GitHub Desktop.
This sample BaseClass implements some functions to register js code to ScriptManager
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class BasePage : System.Web.UI.Page | |
{ | |
/// <summary> | |
/// Creates an instance of a Base Page | |
/// </summary> | |
public BasePage() | |
{ | |
//some init logic if you want =P | |
} | |
/// <summary> | |
/// Inserts the jQuery code between a $(document).ready(function() | |
/// code block so its properly initiated before use | |
/// </summary> | |
/// <param name="jsCodetoRun"></param> | |
/// <returns></returns> | |
private string formatjQueryCode(string jsCodetoRun) | |
{ | |
StringBuilder sb = new StringBuilder(); | |
sb.AppendLine("$(document).ready(function () {"); | |
sb.AppendLine(jsCodetoRun); | |
sb.AppendLine(" });"); | |
return sb.ToString(); | |
} | |
/// <summary> | |
/// Registers JavaScript code in the ScriptManager according to the | |
/// type of postback | |
/// </summary> | |
/// <param name="jsCodetoRun">The JavaScript code that you want to inject. | |
/// Keep in mind that all jQUery code will be put inside a $(document).ready(function() { /*jQuery code*/ }); block</param> | |
/// <param name="isjQueryCode">Pass false if not jQuery but simple JavaScript</param> | |
public void runJavaScriptCode(string jsCodetoRun, bool isjQueryCode=true) | |
{ | |
ScriptManager requestSM = ScriptManager.GetCurrent(this); | |
if (requestSM != null && requestSM.IsInAsyncPostBack) | |
{ | |
ScriptManager.RegisterClientScriptBlock(this, | |
typeof(Page), | |
Guid.NewGuid().ToString(), | |
isjQueryCode ? formatjQueryCode(jsCodetoRun) : jsCodetoRun, | |
true); | |
} | |
else | |
{ | |
ClientScript.RegisterClientScriptBlock(typeof(Page), | |
Guid.NewGuid().ToString(), | |
isjQueryCode ? formatjQueryCode(jsCodetoRun) : jsCodetoRun, | |
true); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment