views:

265

answers:

2

PLEASE NOTE: I've answered my own question with a link to an answer to a similar question. I'll accept that answer once I'm allowed to (unless anyone comes up with a better answer meantime).

I have a database column defined as NVARCHAR(1000) NOT NULL DEFAULT(N'') - in other words, a non-nullable text column with a default value of blank.

I have a model class generated by the Linq-to-SQL Classes designer, which correctly identifies the property as not nullable.

I have a TextAreaFor in my view for that property. I'm using UpdateModel in my controller to fetch the value from the form and populate the model object.

If I view the web page and leave the text area blank, UpdateModel insists on setting the property to NULL instead of empty string. (Even if I set the value to blank in code prior to calling UpdateModel, it still overwrites that with NULL). Which, of course, causes the subsequent database update to fail.

I could check all such properties for NULL after calling UpdateModel, but that seems ridiculous - surely there must be a better way?

Please don't tell me I need a custom model binder for such a simple scenario...!

+2  A: 

Might be duplicate or something in the line of this:

http://stackoverflow.com/questions/2585172/mvc-binding-form-data-problem/2586121#2586121

I fear custom model binder will be necessary. ;)

mare
Thanks. Jab's answer to that question was useful.
Gary McGill
@mare: can you update your link to point to the question itself, rather than your answer? Then I'll accept it.
Gary McGill
ok, did it. thx
mare
A: 

You might want to use a partial class implementation of your entity that implements the on property changed handler for that particular property. When you detect that the property has been changed to NULL, simply change it to string.Empty. That way anytime NULL is assigned to the property it gets reset to the empty string.

tvanfosson
@tvanfosson: I could, but then I'd have to repeat the same code dozens of times (and worse - I'd probably be creating the partial classes just to do that in many cases). See my own answer with a link to a much cleaner solution.
Gary McGill
if that's the behavior you always want, I suppose that would do the trick. It has the inverse problem of storing empty strings, though, if the column is nullable.
tvanfosson
@tvanfosson: true, if you mean changing the default binder - but the same answer also describes how to do this on a per-property basis using data annotations.
Gary McGill