当前位置: 首页>>代码示例>>C#>>正文


C# ModelBinding.ModelBindingContext类代码示例

本文整理汇总了C#中Microsoft.AspNet.Mvc.ModelBinding.ModelBindingContext的典型用法代码示例。如果您正苦于以下问题:C# ModelBindingContext类的具体用法?C# ModelBindingContext怎么用?C# ModelBindingContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


ModelBindingContext类属于Microsoft.AspNet.Mvc.ModelBinding命名空间,在下文中一共展示了ModelBindingContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: BindModelAsync

        public async Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext)
        {
            var binderType = ResolveBinderType(bindingContext);
            if (binderType != null)
            {
                var binder = (IModelBinder)Activator.CreateInstance(binderType);

                var collectionBinder = binder as ICollectionModelBinder;
                if (collectionBinder != null &&
                    bindingContext.Model == null &&
                    !collectionBinder.CanCreateInstance(bindingContext.ModelType))
                {
                    // Able to resolve a binder type but need a new model instance and that binder cannot create it.
                    return null;
                }

                var result = await binder.BindModelAsync(bindingContext);
                var modelBindingResult = result != null ?
                    result :
                    new ModelBindingResult(model: null, key: bindingContext.ModelName, isModelSet: false);

                // Were able to resolve a binder type.
                // Always tell the model binding system to skip other model binders i.e. return non-null.
                return modelBindingResult;
            }

            return null;
        }
开发者ID:ryanbrandenburg,项目名称:Mvc,代码行数:28,代码来源:GenericModelBinder.cs

示例2: BindModelAsync

        public Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType == typeof(DateTime) || bindingContext.ModelType == typeof(DateTime?))
            {
                var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;

                //if (Controls.Global.UserInfo != null)
                {
                    displayFormat = AppSettings.DateFormat;//Controls.Global.UserInfo.FormatDate;
                }

                var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

                if (!string.IsNullOrEmpty(displayFormat) && value != null && !string.IsNullOrEmpty(value.FirstOrDefault()))
                {
                    DateTime date;
                    //displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
                    // use the format specified in the DisplayFormat attribute to parse the date
                    if (DateTime.TryParseExact(value.FirstOrDefault(), displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
                    {
                        bindingContext.Model = date;
                        return Task.FromResult(new ModelBindingResult());
                    }
                    else
                    {
                        bindingContext.ModelState.AddModelError(
                            bindingContext.ModelName,
                            string.Format("{0} is an invalid date format", value.FirstOrDefault())
                        );
                    }
                }
            }

            return Task.FromResult(new ModelBindingResult());
        }
开发者ID:john-pham,项目名称:hapgo,代码行数:35,代码来源:DateTimeModelBinder.cs

示例3: GetFormFilesAsync

        private async Task<List<IFormFile>> GetFormFilesAsync(ModelBindingContext bindingContext)
        {
            var request = bindingContext.OperationBindingContext.HttpContext.Request;
            var postedFiles = new List<IFormFile>();
            if (request.HasFormContentType)
            {
                var form = await request.ReadFormAsync();

                foreach (var file in form.Files)
                {
                    ContentDispositionHeaderValue parsedContentDisposition;
                    ContentDispositionHeaderValue.TryParse(file.ContentDisposition, out parsedContentDisposition);

                    // If there is an <input type="file" ... /> in the form and is left blank.
                    if (parsedContentDisposition == null ||
                        (file.Length == 0 &&
                         string.IsNullOrEmpty(HeaderUtilities.RemoveQuotes(parsedContentDisposition.FileName))))
                    {
                        continue;
                    }

                    var modelName = HeaderUtilities.RemoveQuotes(parsedContentDisposition.Name);
                    if (modelName.Equals(bindingContext.ModelName, StringComparison.OrdinalIgnoreCase))
                    {
                        postedFiles.Add(file);
                    }
                }
            }

            return postedFiles;
        }
开发者ID:notami18,项目名称:Mvc,代码行数:31,代码来源:FormFileModelBinder.cs

示例4: BindModelAsync

        public Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext)
        {
            if(bindingContext.ModelType != typeof(Currency))
            {
                return ModelBindingResult.NoResultAsync;
            }

            var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            if(valueProviderResult == ValueProviderResult.None)
            {
                return ModelBindingResult.FailedAsync(bindingContext.ModelName);
            }

            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);
            var value = valueProviderResult.FirstValue;
            if(string.IsNullOrEmpty(value))
            {
                return ModelBindingResult.FailedAsync(bindingContext.ModelName);
            }

            var model = (Currency)value;
            if(model == null)
            {
                return ModelBindingResult.FailedAsync(bindingContext.ModelName);
            }

            var validationNode = new ModelValidationNode(
                bindingContext.ModelName,
                bindingContext.ModelMetadata,
                model
            );

            return ModelBindingResult.SuccessAsync(bindingContext.ModelName, model, validationNode);
        }
开发者ID:OctopusSamples,项目名称:OctoFXvNext,代码行数:34,代码来源:CurrencyBinder.cs

示例5: BindModelAsync

        public virtual async Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext)
        {
            ModelBindingHelper.ValidateBindingContext(bindingContext);
            if (!CanBindType(bindingContext.ModelType))
            {
                return null;
            }

            var mutableObjectBinderContext = new MutableObjectBinderContext()
            {
                ModelBindingContext = bindingContext,
                PropertyMetadata = GetMetadataForProperties(bindingContext),
            };

            if (!(await CanCreateModel(mutableObjectBinderContext)))
            {
                return null;
            }

            EnsureModel(bindingContext);
            var result = await CreateAndPopulateDto(bindingContext, mutableObjectBinderContext.PropertyMetadata);

            // post-processing, e.g. property setters and hooking up validation
            ProcessDto(bindingContext, (ComplexModelDto)result.Model);
            return new ModelBindingResult(
                bindingContext.Model,
                bindingContext.ModelName,
                isModelSet: true);
        }
开发者ID:AndersBillLinden,项目名称:Mvc,代码行数:29,代码来源:MutableObjectModelBinder.cs

示例6: BindModelAsync

        public async Task<bool> BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType == typeof(ComplexModelDto))
            {
                ModelBindingHelper.ValidateBindingContext(bindingContext,
                                                          typeof(ComplexModelDto),
                                                          allowNullModel: false);

                var dto = (ComplexModelDto)bindingContext.Model;
                foreach (var propertyMetadata in dto.PropertyMetadata)
                {
                    var propertyBindingContext = new ModelBindingContext(bindingContext)
                    {
                        ModelMetadata = propertyMetadata,
                        ModelName = ModelBindingHelper.CreatePropertyModelName(bindingContext.ModelName,
                                                                               propertyMetadata.PropertyName)
                    };

                    // bind and propagate the values
                    // If we can't bind, then leave the result missing (don't add a null).
                    if (await bindingContext.ModelBinder.BindModelAsync(propertyBindingContext))
                    {
                        var result = new ComplexModelDtoResult(propertyBindingContext.Model,
                                                               propertyBindingContext.ValidationNode);
                        dto.Results[propertyMetadata] = result;
                    }
                }

                return true;
            }

            return false;
        }
开发者ID:Nakro,项目名称:Mvc,代码行数:33,代码来源:ComplexModelDtoModelBinder.cs

示例7: BindModelAsync

        public async Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext.BinderType == null)
            {
                // Return null so that we are able to continue with the default set of model binders,
                // if there is no specific model binder provided.
                return null;
            }

            var requestServices = bindingContext.OperationBindingContext.HttpContext.RequestServices;
            var createFactory = _typeActivatorCache.GetOrAdd(bindingContext.BinderType, _createFactory);
            var instance = createFactory(requestServices, arguments: null);

            var modelBinder = instance as IModelBinder;
            if (modelBinder == null)
            {
                throw new InvalidOperationException(
                    Resources.FormatBinderType_MustBeIModelBinder(
                        bindingContext.BinderType.FullName,
                        typeof(IModelBinder).FullName));
            }

            var result = await modelBinder.BindModelAsync(bindingContext);

            var modelBindingResult = result != null ?
                new ModelBindingResult(result.Model, result.Key, result.IsModelSet, result.ValidationNode) :
                new ModelBindingResult(model: null, key: bindingContext.ModelName, isModelSet: false);

            // A model binder was specified by metadata and this binder handles all such cases.
            // Always tell the model binding system to skip other model binders i.e. return non-null.
            return modelBindingResult;
        }
开发者ID:RehanSaeed,项目名称:Mvc,代码行数:32,代码来源:BinderTypeBasedModelBinder.cs

示例8: BindModelCoreAsync

        private async Task<ModelBindingResult> BindModelCoreAsync(ModelBindingContext bindingContext)
        {
            var requestServices = bindingContext.OperationBindingContext.HttpContext.RequestServices;
            var createFactory = _typeActivatorCache.GetOrAdd(bindingContext.BinderType, _createFactory);
            var instance = createFactory(requestServices, arguments: null);

            var modelBinder = instance as IModelBinder;
            if (modelBinder == null)
            {
                throw new InvalidOperationException(
                    Resources.FormatBinderType_MustBeIModelBinder(
                        bindingContext.BinderType.FullName,
                        typeof(IModelBinder).FullName));
            }

            var result = await modelBinder.BindModelAsync(bindingContext);

            var modelBindingResult = result != ModelBindingResult.NoResult ?
                result :
                ModelBindingResult.Failed(bindingContext.ModelName);

            // A model binder was specified by metadata and this binder handles all such cases.
            // Always tell the model binding system to skip other model binders i.e. return non-null.
            return modelBindingResult;
        }
开发者ID:4myBenefits,项目名称:Mvc,代码行数:25,代码来源:BinderTypeBasedModelBinder.cs

示例9: BindModelAsync

        public Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext)
        {
            // This method is optimized to use cached tasks when possible and avoid allocating
            // using Task.FromResult. If you need to make changes of this nature, profile
            // allocations afterwards and look for Task<ModelBindingResult>.

            var binderType = ResolveBinderType(bindingContext);
            if (binderType == null)
            {
                return ModelBindingResult.NoResultAsync;
            }

            var binder = (IModelBinder)Activator.CreateInstance(binderType);

            var collectionBinder = binder as ICollectionModelBinder;
            if (collectionBinder != null &&
                bindingContext.Model == null &&
                !collectionBinder.CanCreateInstance(bindingContext.ModelType))
            {
                // Able to resolve a binder type but need a new model instance and that binder cannot create it.
                return ModelBindingResult.NoResultAsync;
            }

            return BindModelCoreAsync(bindingContext, binder);
        }
开发者ID:huoxudong125,项目名称:Mvc,代码行数:25,代码来源:GenericModelBinder.cs

示例10: BindModelCoreAsync

        private async Task<ModelBindingResult> BindModelCoreAsync(ModelBindingContext bindingContext)
        {
            object value;
            if (bindingContext.ModelType == typeof(IFormFile))
            {
                var postedFiles = await GetFormFilesAsync(bindingContext);
                value = postedFiles.FirstOrDefault();
            }
            else if (typeof(IEnumerable<IFormFile>).IsAssignableFrom(bindingContext.ModelType))
            {
                var postedFiles = await GetFormFilesAsync(bindingContext);
                value = ModelBindingHelper.ConvertValuesToCollectionType(bindingContext.ModelType, postedFiles);
            }
            else
            {
                // This binder does not support the requested type.
                Debug.Fail("We shouldn't be called without a matching type.");
                return ModelBindingResult.NoResult;
            }

            if (value == null)
            {
                return ModelBindingResult.Failed(bindingContext.ModelName);
            }
            else
            {
                bindingContext.ValidationState.Add(value, new ValidationStateEntry() { SuppressValidation = true });
                bindingContext.ModelState.SetModelValue(
                    bindingContext.ModelName,
                    rawValue: null,
                    attemptedValue: null);

                return ModelBindingResult.Success(bindingContext.ModelName, value);
            }
        }
开发者ID:huoxudong125,项目名称:Mvc,代码行数:35,代码来源:FormFileModelBinder.cs

示例11: BindModelAsync

        public async Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext)
        {
            ModelBindingHelper.ValidateBindingContext(bindingContext);

            if (!TypeHelper.HasStringConverter(bindingContext.ModelType))
            {
                // this type cannot be converted
                return null;
            }

            var valueProviderResult = await bindingContext.ValueProvider.GetValueAsync(bindingContext.ModelName);
            if (valueProviderResult == null)
            {
                return null; // no entry
            }

            object newModel;
            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);
            try
            {
                newModel = valueProviderResult.ConvertTo(bindingContext.ModelType);
                ModelBindingHelper.ReplaceEmptyStringWithNull(bindingContext.ModelMetadata, ref newModel);
                return new ModelBindingResult(newModel, bindingContext.ModelName, isModelSet: true);
            }
            catch (Exception ex)
            {
                bindingContext.ModelState.TryAddModelError(bindingContext.ModelName, ex);
            }

            // Were able to find a converter for the type but conversion failed.
            // Tell the model binding system to skip other model binders i.e. return non-null.
            return new ModelBindingResult(model: null, key: bindingContext.ModelName, isModelSet: false);
        }
开发者ID:AndersBillLinden,项目名称:Mvc,代码行数:33,代码来源:TypeConverterModelBinder.cs

示例12: GetEnumerableBinder

        private static Type GetEnumerableBinder(ModelBindingContext context)
        {
            var modelTypeArguments = GetGenericBinderTypeArgs(typeof(IEnumerable<>), context.ModelType);
            if (modelTypeArguments == null)
            {
                return null;
            }

            if (context.Model == null)
            {
                // GetCollectionBinder has already confirmed modelType is not compatible with ICollection<T>. Can a
                // List<T> (the default CollectionModelBinder type) instance be used instead of that exact type?
                // Likely this will succeed only if the property type is exactly IEnumerable<T>.
                var closedListType = typeof(List<>).MakeGenericType(modelTypeArguments);
                if (!context.ModelType.IsAssignableFrom(closedListType))
                {
                    return null;
                }
            }
            else
            {
                // A non-null instance must be updated in-place. For that the instance must also implement
                // ICollection<T>. For example an IEnumerable<T> property may have a List<T> default value.
                var closedCollectionType = typeof(ICollection<>).MakeGenericType(modelTypeArguments);
                if (!closedCollectionType.IsAssignableFrom(context.Model.GetType()))
                {
                    return null;
                }
            }

            return typeof(CollectionModelBinder<>).MakeGenericType(modelTypeArguments);
        }
开发者ID:ryanbrandenburg,项目名称:Mvc,代码行数:32,代码来源:GenericModelBinder.cs

示例13: ResolveBinderType

        private static Type ResolveBinderType(ModelBindingContext context)
        {
            var modelType = context.ModelType;

            return GetArrayBinder(modelType) ??
                GetCollectionBinder(modelType) ??
                GetDictionaryBinder(modelType) ??
                GetEnumerableBinder(context) ??
                GetKeyValuePairBinder(modelType);
        }
开发者ID:ryanbrandenburg,项目名称:Mvc,代码行数:10,代码来源:GenericModelBinder.cs

示例14: BindModel

 public object BindModel(ActionContext actionContext, ModelBindingContext bindingContext)
 {
     var cart = actionContext.HttpContext.Session[SessionKey];
     if (cart == null)
     {
         cart = Uitilties.ObjectToByteArray(new Cart());
         actionContext.HttpContext.Session[SessionKey] = cart;
     }
     return cart;
 }
开发者ID:Codeflyers,项目名称:EC-GitHub,代码行数:10,代码来源:CartModelBinder.cs

示例15: BindModelAsync

        public Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType == typeof(HttpRequestMessage))
            {
                var model = bindingContext.OperationBindingContext.HttpContext.GetHttpRequestMessage();
                return Task.FromResult(new ModelBindingResult(model, bindingContext.ModelName, isModelSet: true));
            }

            return Task.FromResult<ModelBindingResult>(null);
        }
开发者ID:AndersBillLinden,项目名称:Mvc,代码行数:10,代码来源:HttpRequestMessageModelBinder.cs


注:本文中的Microsoft.AspNet.Mvc.ModelBinding.ModelBindingContext类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。