views:

195

answers:

1

I have an MVC 2 application that utilises forms. The required fields within the form are set using attributes that update the model metadata. The form fields are created using the MVC HtmlHelper method : Html.EditorFor.

This works fine so far as validation is concerned, but it seems that by default the required fields are not displayed to the user (for example by appending a * to the control).

If I wanted to provide some custom means of displaying this fact to the user (lets immagine I want to change the background colour of the edit control for example), where is the best place to do it? Would I need to create a custom html helper to replace EditorFor? I tried but it seemed difficult to gain access to the metadata for the correct property. I already have a custom ModelMetaDataProvider so there is no problem adding it there if that is the correct place.

+1  A: 

Rather than a custom helper, you probably want a custom template. Your custom template would mimic the standard template, except that you'd have the marker for required fields. See Brad Wilson's blog article on templating in MVC2 for more info on how to go about it, but the basic idea is to generate a ViewUserControl in the Shared/EditorTemplates (and Shared/DisplayTemplates) folders strongly typed to your model. You can then use EditorFor and DisplayFor and specify the template name to use, though I think it will also pick up the template if it's strongly typed to your model.

tvanfosson
Thanks for the quick response. I am already using display/editor templates and considered this as an option as you can access the modelmetadata from there. I guess if I did I'd need to provide templates for each datatype?
Nigel
I tried it and it worked a treat for regular textboxes just by creating a new template for string. Other inputs and selects shouldn't be too hard. If nobody else suggests a better alternative I'll mark this answer and post some example code.
Nigel
If you use the standard helpers from within the template, things work pretty much as expected so you won't need templates for the standard data types, just your models. You might also be able to do something with javascript to add something after required fields using `window.mvcClientValidationMetadata` to find the fields with ValidationType `required` and add the flag.
tvanfosson
@Nigel -- so you're creating a new template for both your model and the string datatype or just the string datatype?
tvanfosson
I have templates for my view models already. Seeing how most value types seem to default to the string template, that seemed the appropriate template to change to cater for the text boxes (which has worked fine). Is there a better approach? I'll try the javascript approach as well.
Nigel
If it works for you that seems ok. Did you factor in a way to turn it off?
tvanfosson
No I didn't factor in a way to turn it off as I don't think I will need it for this project. Thanks for the help.
Nigel