3

Is there any way that can I set default value as Empty.string in Model.

I have a column Name in the Model its not null field in the database with default value is Empty.string

is there any way that I can set this default property in the Model for this column?

Thanks

kumar
  • 2,944
  • 18
  • 60
  • 89

3 Answers3

14

There is a setting for this which you can configure by overriding the default model binder as follows:

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

then configure this as the default model binder in application start in the global.asax:

ModelBinders.Binders.DefaultBinder = new EmptyStringModelBinder();

and there you go, no more null strings.

Rob West
  • 5,189
  • 1
  • 27
  • 42
4
MyProperty {get{return myProperty??""}}
Arunprasanth K V
  • 20,733
  • 8
  • 41
  • 71
BlackTigerX
  • 6,006
  • 7
  • 38
  • 48
0

A cleaner alternative is to provide a custom ModelMetadataProvider instead of creating a ModelBinder which modifies the ModelMetadata.

public class EmptyStringDataAnnotationsModelMetadataProvider : System.Web.Mvc.DataAnnotationsModelMetadataProvider 
{
    protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
    {
        var modelMetadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
        modelMetadata.ConvertEmptyStringToNull = false;
        return modelMetadata;
    }
}

Then in Application_Start()

ModelMetadataProviders.Current = new EmptyStringDataAnnotationsModelMetadataProvider();
LostInComputer
  • 15,188
  • 4
  • 41
  • 49