开发者

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

开发者 https://www.devze.com 2023-02-17 02:07 出处:网络
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 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


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.


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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号