Ever wanted to use your own custom HtmlHelper extensions inside your NHaml views? I wanted that, but I got this error:
error CS1061: ‘System.Web.Mvc.HtmlHelper’ does not contain a definition for ‘WhyOhWhy’ and no extension method ‘WhyOhWhy’ accepting a first argument of type ‘System.Web.Mvc.HtmlHelper’ could be found (are you missing a using directive or an assembly reference?)
The problem was that NHaml would not know that there existed some extensions of the HtmlHelper class in some obscure assembly somewhere inside my web app. To do this, you need to tell NHaml exactly which assembly and which namespaces to include in its search. Here is how to do it:
In your web.config, beneath the <configSections> node, add this
1 |
<section name="nhamlViewEngine" type="MvcContrib.NHamlViewEngine.Configuration.NHamlViewEngineSection, MvcContrib.NHamlViewEngine" /> |
– and then outside of <configSections>, add this:
1 |
<nhamlViewEngine configSource="NHaml.config"/> |
This will cause NHaml.config to be included. We could just have embedded the configuration inside the web.config file, but we want to make separate NHaml.config files for each environment we want to deploy our application in. Then we can turn on NHaml’s compiled view caching feature by flicking the production attribute.
An example NHaml configuration is something like this:
1 2 3 4 5 6 7 8 9 10 11 |
<nhamlViewEngine production="false"> <views> <assemblies> <add assembly="MyAssembly" /> </assemblies> <namespaces> <add namespace="MyAssembly.HtmlHelperExtensions" /> <add namespace="MyAssembly.EvenMoreHtmlHelperExtensions" /> </namespaces> </views> </nhamlViewEngine> |
Suddenly you will gain access to everything inside the specified namespaces inside your NHaml templates. Nifty!