Friday 19 February 2010

Go away “The value '' is invalid”!!!

I’ve been busy working away on an ASP.Net MVC 2 project for the last week a half or so.
Just to get some background on this project. I’m using VS 2010 RC, SQL Server 2008 and the Data Entity Framework that comes with .Net 4.0. I’ve been using the objects created by the EF as my data model and have added the necessary Metadata for validation using an extra class in conjunction with the MetadataType attribute and partial classes. Please see Scott Guthrie’s excellent blog posting on this here http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx.

Everything was setup and I had a simple Title class with one property that had a required field attribute.

   1:  public class TitleMetadata
   2:  {
   3:       [DisplayName("Title")]  
   4:       [Required(ErrorMessage = "Title is required.")]  
   5:       public string MainTitle { get; set; }
   6:  }

I knew the Metadata class was being picked up by my model because the title was being displayed correctly.

<%= Html.LabelFor(m=>m.MainTitle) %>
<%= Html.EditorFor(m => m.MainTitle) %>
<%= Html.ValidationMessageFor(m=>m.MainTitle) %>

However, when I clicked the submit button leaving the Title field blank, instead of seeing the message “Title is required” I was setting "The value '' is invalid.”!

image

After some debugging I discovered that the message wasn’t coming from my metadata file or from MVC itself, but rather it was coming from the EntityFramework’s model. The scalar property I was binding to wasn’t set as Nullable and it was generating an exception in the setter.

image

Once I changed over the value Nullable in the Entity Model, my problem resolved itself!

image

Just something to watch for when using MVC with the EntityFramework!

No comments:

Post a Comment