Wednesday, 19 June 2013

Using Razor to Customise the Templates Used by Html.Display, Html.DisplayFor, HtmlEditor and Html.EditorFor

I recently added a new public repository on GitHub that might be useful to ASP.Net MVC developers:

Essentially, this project provides Razor (C#) alternatives for all of the built-in templates used by the Html.Display / Html.DisplayFor and Html.Editor / Html.EditorFor extension methods.

Writing your own templates isn't that hard but if you wanted to introduce changes across all of the templates in the framework, you'd have quite a lot of templates to write from scratch and there's a bit of subtlety here and there in how they work.

I hope that this project provides a useful starting point for developers wanting to introduce changes to templates within their application.

Some examples of things you can do once you have the templates in place:
  • Change HTML in line with your project's CSS rules
  • Introduce visual effects, such as graphics / words for displaying boolean values etc.
  • Introduce parameterised variations using additionalViewData parameters, e.g. @Html.Editor("EnableWeapons", new { icon = "warning" })
  • Change surrounding HTML generated by Html.DisplayForModel to support your project's CSS layout framework
Sorry, I forgot to mention the date-pickers! You'll be able to add date pickers to your date editors.

In line with the built-in ASP.Net MVC editor templates, HTML5 input elements are generated for some data types.

There's a full write up in the README visible on the link above.

I've also added some additional extension methods. You can now use Html.EditorSection and
Html.DisplaySection to display individual properties of your model together with some surrounding HTML, labels and (for editors) validation messages. There's another post on the way with more about this.