Posted on Wednesday April 4, 2012

Razor: Defining a section inside a HTML helper extension method

If you need to inject a generic section of code to your view you’d typically write an extension method for the HtmlHelper class and return an MVCHtmlString. You can also create an extension method that will add a @section Name to the view, using something like the snippet below:

public static MvcHtmlString ShowModalForPage(this HtmlHelper helper, int pageIndex)
{
	WebViewPage page = helper.ViewDataContainer as WebViewPage;
	if (page != null)
	{
		page.DefineSection("Head", () =>
		{
			StringBuilder builder = new StringBuilder();
			builder.Append(@"<script type=""text/javascript"">");
			builder.Append("$(document).ready(function () ");
			builder.Append("{");
			builder.Append("    showModal(" + pageIndex+ " );");
			builder.Append("});");
			builder.Append("</script>");
			page.Write(MvcHtmlString.Create(builder.ToString()));
		});
	}
	
	return MvcHtmlString.Empty;
}

You still need to return a MvcHtmlString regardless of the fact it’s being added to the page via the WebViewPage.Write method.