Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In MVC 3, how do I make the default model binder treat empty strings as "Empty" rather than "NULL"?

I'm using Entity Framework Code-First with POCOs for my database interaction. I have a field that is optional called "Title".

When I get the object from the form, the default model binder automagically makes "Title" null instead of empty.

How do I get the model binder to return an empty string instead of null?

Thanks for any help

like image 924
quakkels Avatar asked Oct 13 '11 23:10

quakkels


2 Answers

Old question, but in MVC4 you can add this to your POCO property:

[DisplayFormat(ConvertEmptyStringToNull = false)]
like image 153
freedomn-m Avatar answered Oct 17 '22 02:10

freedomn-m


You are requesting non-standard behaviour, so you need non-standard solution. Extend default model binder, override its CreateModel method - do what you want for specific cases, and return base.CreateModel for others.

Dont forget to register it as default model binder at application start.

like image 5
rouen Avatar answered Oct 17 '22 03:10

rouen