How to set Default value as Empty string in Model

2019-04-12 02:02发布

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

3条回答
对你真心纯属浪费
2楼-- · 2019-04-12 02:03

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.

查看更多
Ridiculous、
3楼-- · 2019-04-12 02:12

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();
查看更多
叛逆
4楼-- · 2019-04-12 02:28
MyProperty {get{return myProperty??""}}
查看更多
登录 后发表回答