本文整理汇总了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;
}
示例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());
}
示例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;
}
示例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);
}
示例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);
}
示例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;
}
示例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;
}
示例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;
}
示例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);
}
示例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);
}
}
示例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);
}
示例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);
}
示例13: ResolveBinderType
private static Type ResolveBinderType(ModelBindingContext context)
{
var modelType = context.ModelType;
return GetArrayBinder(modelType) ??
GetCollectionBinder(modelType) ??
GetDictionaryBinder(modelType) ??
GetEnumerableBinder(context) ??
GetKeyValuePairBinder(modelType);
}
示例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;
}
示例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);
}