Display templatesMVC has a bunch of handy helpers that we can use to create our views efficiently and effectively. One such helper is the display templates that are used within views.
DisplayFor(Func<TModel, TValue> expression)function uses the type of the property in the expression to display the property value.
Defining custom templatesWe can override the default templates by placing our custom display templates into the path
Views/Shared/DisplayTemplates/<type>.cshtml. They are structured like any MVC partial view. An example usage could be adding a dollar sign to the front of a
UIHint attributeTo use a custom display template that isn't based on the name of the type, we can set a
UIHintattribute on the property. So we could make a 'Currency' display template instead of assuming that all decimals are dollar amounts. To do this we would simply rename our
decimal.cshtmlfile above to
Currency.cshtmland apply the
UIHintattribute to the model property like so:
Editor templatesEditor templates can be overridden in the same way using the
EditorForfunction and placing the custom templates in
Passing additional dataIt may be necessary to provide more than just a property to the custom template. For example if we want to display a list of radio buttons with one of them selected. This could be achieved by passing in the list of options as 'view data' and having the property as an
int?which would represents the index of the selected option. MVC provides an overload that allows us to pass in this additional view data to the custom template,
EditorFor(Func<TModel, TValue> expression, Object additionalViewData).