kumar
kumar

Reputation: 2944

How to set Default value as Empty string in Model in asp.net mvc application

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

Upvotes: 3

Views: 4574

Answers (3)

BlackTigerX
BlackTigerX

Reputation: 6146

MyProperty {get{return myProperty??""}}

Upvotes: 4

LostInComputer
LostInComputer

Reputation: 15420

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();

Upvotes: 0

Rob West
Rob West

Reputation: 5241

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.

Upvotes: 14

Related Questions