NMoneys.Web is website, built with ASP.NET MVC. I might as well share with you a couple of things I learnt.
Views
I like Razor a lot. Once you use it, you do not want to hear about the “old” Webforms view engine anymore. Unfortunately, even if you do not use, it is still there, lingering around and being tried for every view.
You can find the tip to remove unused view engines in many places. Now there is one place more:
The TwoLevelCache
is a simple IViewLocationCache
decorator that uses a per-request dictionary to speed view location lookups.
Controllers
Probably the single biggest performance boost you can give a a website is do as little as possible. One way of achieving this sweet spot is caching. And the simplest way to cache controller methods is the output cache.
In this cache, the whole result of the controller is cached. Simply decorate the controller action with an OutputCacheAttribute
and, amongst other properties, point the cache profile that will hold the information.
And remember to configure the profile in Web.config:
Html Helpers
Sometimes one does not need a full-blown partial view or a Razor helper. Most of the time is enough to encapsulate a small bit of reusable markup inside an Html Helper extension method. In here markup is created from code. Of course there are multiple ways to generate it, I will mention some:
Format your strings
I really, really, really did not want to mention it, but since I saw an example of this “technique” recently (I kid you not)…
One simply creates a string that contains the html to be returned and use format placeholders to inject the values. I did that in 1996 (first programming job). I still look behind me in dark alleys in case the maintainer of that code finally got me.
The MVC way
What we can do with out-of-the-box MVC is use the TagBuilder
class to compose our tags, which will return a nice IHtmlString
that will be rendered the view:
Certainly more robust than string-formatting literals but still verbose. Furthermore, the API forces you to code from the inside out, obfuscating the structure of the generated HTML.
FUBU it
One of the multiple sub-projects of FubuMVC, is the HtmlTags project. Basically is TagBuilder
done right. It leverages a simple to use fluent API and yields very, very terse and readable code that indicates hierarchy by nesting calls, so there is little doubt of the structure of the HTML:
Furthermore, since what is returned is not some sort of string, but a composable object model, the tags can be further customized in the view, really useful for one/twice time change of the rendered HTML. Wicked.