csharp BetterDefaultModelBinder意味着所有集合属性都被实例化为空集合而不是null。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp BetterDefaultModelBinder意味着所有集合属性都被实例化为空集合而不是null。相关的知识,希望对你有一定的参考价值。

ModelBinders.Binders.DefaultBinder = new BetterDefaultModelBinder();
    public class BetterDefaultModelBinder : DefaultModelBinder
    {
        protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
        {
            var model = base.CreateModel(controllerContext, bindingContext, modelType);

            if (model == null || model is IEnumerable)
                return model;

            foreach (var property in modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                object value = property.GetValue(model);
                if (value != null)
                    continue;

                if (property.PropertyType.IsArray)
                {
                    value = Array.CreateInstance(property.PropertyType.GetElementType(), 0);
                    property.SetValue(model, value);
                }
                else if (property.PropertyType.IsGenericType)
                {
                    Type typeToCreate;
                    Type genericTypeDefinition = property.PropertyType.GetGenericTypeDefinition();
                    if (genericTypeDefinition == typeof(IDictionary<,>))
                    {
                        typeToCreate = typeof(Dictionary<,>).MakeGenericType(property.PropertyType.GetGenericArguments());
                    }
                    else if (genericTypeDefinition == typeof (IEnumerable<>) ||
                             genericTypeDefinition == typeof (ICollection<>) ||
                             genericTypeDefinition == typeof (IList<>))
                    {
                        typeToCreate = typeof(List<>).MakeGenericType(property.PropertyType.GetGenericArguments());
                    }
                    else
                    {
                        continue;
                    }

                    value = Activator.CreateInstance(typeToCreate);
                    property.SetValue(model, value);
                }
            }

            return model;
        }
    }

以上是关于csharp BetterDefaultModelBinder意味着所有集合属性都被实例化为空集合而不是null。的主要内容,如果未能解决你的问题,请参考以下文章

csharp 例如-CSHARP-GroupDocs.Conversion.Examples.CSharp渲染,RenderPSDImageAsPath.cs

csharp 实例-CSHARP-GroupDocs.Conversion.Examples.CSharp变频-ConvertTopresentationAsPath.cs

csharp 实例-CSHARP-GroupDocs.Conversion.Examples.CSharp变频-ConvertTopresentationAsPath.cs

csharp 实例-CSHARP-GroupDocs.Conversion.Examples.CSharp变频-ConvertTopresentationAsPath.cs

csharp 例如-CSHARP-GroupDocs.Search.Examples.CSharp索引,AddDocumentToIndex.cs

csharp 例如-CSHARP-GroupDocs.Search.Examples.CSharp索引,AddDocumentToIndexAsynchronously.cs