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

北慕城南 提交于 2019-12-06 08:38:32

问题


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


回答1:


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.




回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/5331488/how-to-set-default-value-as-empty-string-in-model-in-asp-net-mvc-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!