ASP MVC 2: Custom Display of Required Form Element Based on ModelMetaData
I have an MVC 2 application that uses forms. The required fields on the form are set using attributes that update the model's metadata . Form fields are created using the MVC HtmlHelper: Html.EditorFor method .
This works well with regards to validation, but it seems that by default the required fields are not displayed to the user (for example by adding * to the control).
If I wanted to provide some custom ways to display this fact to the user (lets immagine I want to change the background color for an edit control, for example) where is the best place to do this? Do I need to create a custom html helper to replace EditorFor? I tried but found it difficult to access the metadata for the correct property. I already have a custom ModelMetaDataProvider so there is no problem adding it as long as it is in the right place.
a source to share
Instead of a custom helper, you probably want to create a custom template. Your custom template will mimic the standard template, except that you have a marker for the required fields. See Brad Wilson 's blog post on Templates in MVC2 for more information on how to do this, but the basic idea is to create a ViewUserControl in Shared / EditorTemplates (and Shared / DisplayTemplates) packages that are strongly typed for your model. You can then use EditorFor and DisplayFor and provide a name for the template to use, although I think it will pick up the template as well if it is strongly typed for your model.
a source to share