views:

601

answers:

2

I initialize my strings to blank, not null. Which worked fine in MVC 1, using tryupdatemodel in that any text entries that had no text in them would be set to a blank string, in MVC 2 RC2 apparently (at least from my testing) it sets them to null / nothing. So now I'm getting errors from my validation layer which requires those to be blanks not null. Another problem with it that I have found is that now via reflection it calls every property on my objects including the ones I've not specified in a bind include statement and even readonly properties that could not be set.

Any one have an idea of the easiest way to get around these problems without totally changing all my code? Or should I just suck it up and

A: 

About properties that you haven't bound - asp.net mvc 2 rc has this change from input validation to model validation, here is how it works now
I suppose the issue you have with string is also because of changes made in RC2, check out the release notes.

chester89
Yeah, I figured that was probably why it was calling all the properties, I assume it's related to how they fire all the validation properties on the model.The string stuff I'm looking in the release notes for it at this moment.
Solmead
A: 

To fix the string defaulting to null instead of "" I had to do this first:

Public Class NullToEmptyStringModelBinder
Inherits DefaultModelBinder

Protected Overrides Sub SetProperty(ByVal controllerContext As System.Web.Mvc.ControllerContext, ByVal bindingContext As System.Web.Mvc.ModelBindingContext, ByVal propertyDescriptor As System.ComponentModel.PropertyDescriptor, ByVal value As Object)
    If value Is Nothing AndAlso propertyDescriptor.PropertyType Is GetType(String) Then
        value = ""
    End If



    MyBase.SetProperty(controllerContext, bindingContext, propertyDescriptor, value)
End Sub
End Class

And then add to the application start this:

ModelBinders.Binders.DefaultBinder = New NullToEmptyStringModelBinder
Solmead