Reputation: 5266
I have a page with a tab, each tab content is placed as a partial view with some scripts
As a best practice, I want to add all the scripts in the bottom of the page. Since the partial views are unable to access the @section
i placed all the scripts in page itself, it is hard to read.
Tabs are loaded based on permission. Even though user doesnt have permission, still i render those scripts.
How can i add all the scripts referred in page/partial view at the bottom
?
WebForm Context: I think it is similar to accessing the content place holder from a user control
Upvotes: 2
Views: 101
Reputation: 22619
You can do it by writting this with some Extension Method
with the MVCHtmlHelper
Here is the code
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());
}
In your layout design
@RenderSection("Scripts", false)
@this.WriteScriptBlocks()
In Partial View
@model ViewModel
@this.ScriptBlock(
@<script type='text/javascript'>
$(document).ready(function () {
notify('@message', '@Model.Type.ToString()', '@Model.Type.ToString().ToLower()');
});
</script>)
Refer this post
Upvotes: 1