Created
August 29, 2014 09:30
-
-
Save valerysntx/8da8881624e552c00a2e to your computer and use it in GitHub Desktop.
Script Block Templated Delegate for Inline Scripts in Razor Partials
This file contains 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
@RenderSection("Scripts", false) | |
@this.WriteScriptBlocks() |
This file contains 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
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 file contains 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
@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