Unfortunately MVC3 doesn’t respect the [Required] attribute’s AllowEmptyStrings property. When using a class both as an MVC model and as an EF Code First entity this is a problem. What if I want to allow empty strings, but not null values in the database?
The problem lies in the client side validation performed by MVC3. If a property in the model is marked with [Required] the jquery required validator will be enabled. It requires a non-empty string. I would prefer MVC to not emit a required validation if AllowEmptyStrings is true. Unfortunately the MVC code doesn’t honor that flag, but there is a workaround. Create a small attribute derived from RequiredAttribute.
In the Type Safe SelectList Factory post I showed one way to improve the SelectList constructor. Recently I wrote another one, when I needed a SelectList that has the selected item’s index as the value. I used this together with jQuery to get details about the selected item from a separately supplied json array.
I think that ASP.NET MVC is a huge step forward from ASP.NET Web Forms. Still, there are some parts of it that are disappointing. One is the SelectList constructor, that doesn’t use generics and has string parameters for field selection. To create a SelectList from an IEnumerable<> we would do something like this.
IEnumerable<Person> people = GetPeople();
SelectList selectList =new SelectList(people, "Id", "FullName");
IEnumerable<Person> people = GetPeople();
SelectList selectList = new SelectList(people, "Id", "FullName");
This is again one of those places where the compiler won’t be able to help us. Writing member names as strings in the code is just horrible. To remedy this I wrote a factory method with those strings changed into lambdas.
IEnumerable<Person>= GetPeople();
SelectList selectList =
people.ToSelectList(people, p => p.Id, p => p.FullName);
IEnumerable<Person> = GetPeople();
SelectList selectList =
people.ToSelectList(people, p => p.Id, p => p.FullName);
The compiler is my friend. It helps me check for simple spelling mistakes and alerts me when a change in one part of the code base breaks a reference somewhere else.
When developing in ASP.NET Web Forms I have had a hard time with the lack of compilation of aspx pages. As long as the code is in the code behind, errors are catched during compilation. If the code is in the aspx file itself (e.g. data binding code) it doesn’t fail until the page is accessed. A large application with hundreds of pages requires detailed testing to make sure all pages have been accessed.
In ASP.NET MVC (which I really recommend instead of Web Forms) there is a far better way. The views can be included in the project build, catching any simple mistakes when building. Unfortunately it is not a standard setting, but it is easy to add.