Skip to content

Instantly share code, notes, and snippets.

@valerysntx
Created August 29, 2014 09:30
Show Gist options
  • Save valerysntx/8da8881624e552c00a2e to your computer and use it in GitHub Desktop.
Save valerysntx/8da8881624e552c00a2e to your computer and use it in GitHub Desktop.
Script Block Templated Delegate for Inline Scripts in Razor Partials
@RenderSection("Scripts", false)
@this.WriteScriptBlocks()
private const string SCRIPTBLOCK_BUILDER = "ScriptBlockBuilder";
public static MvcHtmlString ScriptBlock(this WebViewPage webPage,
Func<dynamic, HelperResult> template)
{
if (!webPage.IsAjax)
{
var scriptBuilder = webPage.Context.Items[SCRIPTBLOCK_BUILDER]
as StringBuilder ?? new StringBuilder();
scriptBuilder.Append(template(null).ToHtmlString());
webPage.Context.Items[SCRIPTBLOCK_BUILDER] = scriptBuilder;
return new MvcHtmlString(string.Empty);
}
return new MvcHtmlString(template(null).ToHtmlString());
}
public static MvcHtmlString WriteScriptBlocks(this WebViewPage webPage)
{
var scriptBuilder = webPage.Context.Items[SCRIPTBLOCK_BUILDER]
as StringBuilder ?? new StringBuilder();
return new MvcHtmlString(scriptBuilder.ToString());
}
@this.ScriptBlock(
@<script type='text/javascript'>
$(document).ready(function () {
notify('@message', '@Model.Type.ToString()', '@Model.Type.ToString().ToLower()');
});
</script>)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment