0

I have a POCO class for an edit model

class PersonEditModel {
  public string ScreenName{get;set;}
}

It's common for ScreenName to be null when my domain model is converted into this PersonEditModel.

When I present this in MVC 2 form using the html helpers I get back an empty string (if the user didn't add anything into screenname), because the model binder can't tell the difference between empty and null string value.

Is there a way to tell the model binder to automap a particular string value to null?

So, instead of getting back ScreenName as "", I would get back null. When I persist this back to the Domain model, it's alot cleaner for the data model.

CVertex
  • 17,997
  • 28
  • 94
  • 124
  • 1
    http://stackoverflow.com/questions/1263563/modelbinding-for-empty-query-string-parameters-in-asp-net-mvc-2 – grenade Aug 12 '09 at 17:50
  • This guy has the same issue but doesn't have an answer - http://stackoverflow.com/questions/1105131/how-to-get-model-binder-to-leave-null-strings-as-null/1267729#1267729 – CVertex Aug 12 '09 at 18:00

1 Answers1

0

Have you tried adding this attribute? It should be true by defualt but something might be different with your configuration.

[ConvertEmptyStringToNull=true]
public string ScreenName{get;set;} 

Another option that is less clean is to put a private variable behind ScreenName and if its value is an empty string, then return null on the get.

Chris Woolum
  • 2,854
  • 20
  • 20