amiry jd
amiry jd

Reputation: 27585

How to add property annotation globally

For preventing ASP.NET MVC from getting null for string properties, we can add this annotation to string properties:

[DisplayFormat(ConvertEmptyStringToNull = false)]

What I'm looking for, is to this globally (in an entire project). So, I tried to create a custom model binder:

public class NotNullStringModelBinder : DefaultModelBinder {

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
        if(controllerContext == null)
            throw new ArgumentNullException("controllerContext");
        if(bindingContext == null)
            throw new ArgumentNullException("bindingContext");
        var providerResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if(providerResult == null)
            return string.Empty;
        var attemptedValue = providerResult.AttemptedValue;
        return attemptedValue ?? string.Empty;
    }

}

I have added this in (global.asax).Application_Start():

ModelBinders.Binders.Add(typeof(string), new NotNullStringModelBinder());

But it doesn't work and I'm getting null for empty strings in all models. What I missed? Any idea please?

Upvotes: 1

Views: 357

Answers (2)

amiry jd
amiry jd

Reputation: 27585

Thanks to @Kell seems all I needed to do was this:

public class NotNullStringModelBinder : DefaultModelBinder {

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
        bindingContext.ModelMetadata.ConvertEmptyStringToNull = false;
        return base.BindModel(controllerContext, bindingContext);
    }

}

Upvotes: 2

Kell
Kell

Reputation: 3317

The answer is here: ASP.Net MVC 3 bind string property as string.Empty instead of null

(The second answer in the question) It seems you have to bind to the property binding context, not the model binding context

Upvotes: 1

Related Questions