Chris's coding blog

Razor: Defining a section inside a HTML helper extension method

April 04, 2012

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.

asp.net-mvc

I'm Chris Small, a software engineer working in London. This is my tech blog. Find out more about me via GithubStackoverflowResume