How to set default value as empty string in Model in asp.net mvc application

Is there a way to set the default value as Empty.string in Model.

I have a column name in the Model, this is not an empty field in the database with the default value of Empty.string

Is there any way to set this default property in Model for this column?

thank

+3
source share
3 answers

There is a setting for this, which you can configure by overriding the default 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 at the beginning of the application in global.asax:

ModelBinders.Binders.DefaultBinder = new EmptyStringModelBinder();

and there you go, no more than zero lines.

+13
source

MyProperty {get {return myProperty ?? "}}

+4

A simpler alternative is to provide a custom ModelMetadataProvider instead of creating a ModelBinder that modifies 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();
0
source

All Articles