I’ve been working with Razor some recently, and here are a couple of surprises that bit me.
Secondly, I was writing an HtmlHelper extension method. I put the namespace in the pages/namespaces Web.config block, but my Razor view didn’t seem to be able to find it. Apparently, Razor uses a different configuration block for this, which is kinda annoying. For details, check out Razor (MVC 3 RC) HtmlHelper Extensions Not Found on Stack Overflow. According to Marcin Dobosz (who left a comment on that SO page), this is not something they are going to fix/change. However, if you are using Razor, it looks like you can remove the standard pages/namespaces block from the Web.config.
One of the deceptively trickiest parts of any web application, MVC included, is validation. Here are my major concerns with validation:
- Usability. Validation is for users, after all. Validation messages should be clear, and the user should know exactly what they need to do when getting validation errors. Of course, if the form itself has poor usability, chances are the validation will too, so the user experience starts there.
- ViewModel validation. If you are using MVVM, then validation becomes tricky. Often a viewmodel will simple have a copy of an entity in it, which means the DataAnnotation-style validation in MVC 2 will pass right through and work great. However, a viewmodel will sometimes have a subset or some sort of flattening of the entity, which means you’ll again have to repeat yourself. Scott Guthrie’s comments: in general “it depends”. From a DRY perspective it would be ideal if you could put the validation on the model and have your viewmodels reflect/respect that automatically. Having said that, sometimes the shape of ViewModels look differently than Models – in which case having validation automatically transfer between models/viewmodels might be different (for example: if you flatten fields or expose them differently). We’ll try and get more guidance out there that show off how to handle different scenarios.
- Don’t Repeat Yourself. Didn’t I already say this? This time I mean that if you want to check for a specific formatting, say with a RegEx, that RegEx should only appear in the validation system once. So if you are validating URLs with a RegEx, you should make a custom attribute that calls a method IsValidURL, and the RegEx should be in that method.
I’ve used the WebForms validators before, and they generally make development easier, but so far the MVC 2 validation model is looking more robust, and has extensibility points to use 3rd party validation tools like xVal and Castle.