public Task BindModelAsync(ModelBindingContext bindingContext) { // Our binder works only on enumerable types if (!bindingContext.ModelMetadata.IsEnumerableType) { bindingContext.Result = ModelBindingResult.Failed(); return(Task.CompletedTask); } // Get the inputted value through the value provider var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).ToString(); // If that value is null or whitespace, we return null if (string.IsNullOrWhiteSpace(value)) { bindingContext.Result = ModelBindingResult.Success(null); return(Task.CompletedTask); } // The value isn't null or whitespace, // and the type of the model is enumberable. // Get the enumerable's type, and a converter var elementType = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0]; var converter = TypeDescriptor.GetConverter(elementType); // Convert each item in the value list to the enumberable type var values = value.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries) .Select(x => converter.ConvertFromString(x.Trim())).ToArray(); // Create an array of that type, and set it as the Model value var typedValues = Array.CreateInstance(elementType, values.Length); values.CopyTo(typedValues, 0); bindingContext.Model = typedValues; // return a successful result, passing in the Model bindingContext.Result = ModelBindingResult.Success(bindingContext.Model); return(Task.CompletedTask); }
public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } var stringValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).FirstValue; if (bindingContext.ModelType == typeof(DateTime?) && string.IsNullOrEmpty(stringValue)) { bindingContext.Result = ModelBindingResult.Success(null); return(Task.CompletedTask); } bindingContext.Result = DateTime.TryParse(stringValue, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out DateTime result) ? ModelBindingResult.Success(result.Kind == DateTimeKind.Utc ? result : result.ToUniversalTime()) : ModelBindingResult.Failed(); return(Task.CompletedTask); }
public Task BindModelAsync(ModelBindingContext bindingContext) { // bind only enumerable types if (!bindingContext.ModelMetadata.IsEnumerableType) { bindingContext.Result = ModelBindingResult.Failed(); return(Task.CompletedTask); } // Getting the values from the provider var value = bindingContext.ValueProvider .GetValue(bindingContext.ModelName).ToString(); // if value is an empty string or null return success (nothing to bind) if (string.IsNullOrWhiteSpace(value)) { bindingContext.Result = ModelBindingResult.Success(null); return(Task.CompletedTask); } var elementType = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0]; var converter = TypeDescriptor.GetConverter(elementType); // convert each item in the value list var values = value.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries) .Select(x => converter.ConvertFromString(x.Trim())) .ToArray(); // Create an array of that type, and set it as the Model value var typedValues = Array.CreateInstance(elementType, values.Length); values.CopyTo(typedValues, 0); bindingContext.Model = typedValues; // Return a successfull result bindingContext.Result = ModelBindingResult.Success(bindingContext.Model); return(Task.CompletedTask); }
public Task BindModelAsync(ModelBindingContext bindingContext) { // Binder works on Enumerable types if (!bindingContext.ModelMetadata.IsEnumerableType) { bindingContext.Result = ModelBindingResult.Failed(); return(Task.CompletedTask); } // Attain inputted value through value provider var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).ToString(); // string -> reference type. Return null if none provided. if (string.IsNullOrWhiteSpace(value)) { bindingContext.Result = ModelBindingResult.Success(null); return(Task.CompletedTask); } // Get the Eumerable's type and a converter. var elementType = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0]; var converter = TypeDescriptor.GetConverter(elementType); // Convert each item in the value list to the Enumerable type. var values = value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => converter.ConvertFromString(x.Trim())) .ToArray(); // Create an array of that type and set it as the Model value. var typedValues = Array.CreateInstance(elementType, values.Length); values.CopyTo(typedValues, 0); bindingContext.Model = typedValues; // Return success, provide the model. bindingContext.Result = ModelBindingResult.Success(bindingContext.Model); return(Task.CompletedTask); }
public Task BindModelAsync(ModelBindingContext bindingContext) { if (!typeof(DerivationStrategyBase).GetTypeInfo().IsAssignableFrom(bindingContext.ModelType)) { return(Task.CompletedTask); } ValueProviderResult val = bindingContext.ValueProvider.GetValue( bindingContext.ModelName); string key = val.FirstValue as string; if (key == null) { return(Task.CompletedTask); } var networkProvider = (BTCPayNetworkProvider)bindingContext.HttpContext.RequestServices.GetService(typeof(BTCPayNetworkProvider)); var cryptoCode = bindingContext.ValueProvider.GetValue("cryptoCode").FirstValue; var network = networkProvider.GetNetwork <BTCPayNetwork>(cryptoCode ?? "BTC"); try { var data = network.NBXplorerNetwork.DerivationStrategyFactory.Parse(key); if (!bindingContext.ModelType.IsInstanceOfType(data)) { bindingContext.Result = ModelBindingResult.Failed(); bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Invalid derivation scheme"); return(Task.CompletedTask); } bindingContext.Result = ModelBindingResult.Success(data); } catch { bindingContext.Result = ModelBindingResult.Failed(); bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Invalid derivation scheme"); } return(Task.CompletedTask); }
/// <inheritdoc /> public Task BindModelAsync(ModelBindingContext bindingContext) { var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).FirstValue; if (string.IsNullOrEmpty(value)) { bindingContext.Result = ModelBindingResult.Failed(); return(Task.CompletedTask); } // This special case is for UI code that, when written, accidentally relied on MVC 5's tendency to coerce failed // model parse attempts to `null`. if (value == "Nothing selected") { bindingContext.Result = ModelBindingResult.Success(null); return(Task.CompletedTask); } try { bindingContext.Result = ModelBindingResult.Success(_methodInfo.Invoke(null, new[] { value })); return(Task.CompletedTask); } catch (Exception e) { if (ShouldExceptionBeRethrown(e)) { throw; } var exceptionToRecord = GetExceptionToRecord(e); RecordException(bindingContext, exceptionToRecord); bindingContext.Result = ModelBindingResult.Failed(); return(Task.CompletedTask); } }
public async Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext.HttpContext.Request.HasFormContentType) { var formBinder = new FormCollectionModelBinder(); await formBinder.BindModelAsync(bindingContext); if (bindingContext.Result.IsModelSet) { bindingContext.Result = ModelBindingResult.Success(ToJToken((IFormCollection)bindingContext.Result.Model)); } } else { if (bindingContext.HttpContext.Request.ContentType == "application/json") { try { var readStreamTask = new StreamReader(bindingContext.HttpContext.Request.Body).ReadToEndAsync(); var json = await readStreamTask; using (var sr = new StringReader(json)) using (var jtr = new JsonTextReader(sr) { DateParseHandling = DateParseHandling.None }) { bindingContext.Result = ModelBindingResult.Success(JToken.ReadFrom(jtr)); } } catch (Exception ex) { var bindingContextResult = ModelBindingResult.Failed(); bindingContext.Result = bindingContextResult; } } } }
public Task BindModelAsync(ModelBindingContext bindingContext) { //Our binder works only with enumerable types #pragma warning disable CA1062 // Validate arguments of public methods if (!bindingContext.ModelMetadata.IsEnumerableType) #pragma warning restore CA1062 // Validate arguments of public methods { bindingContext.Result = ModelBindingResult.Failed(); return(Task.CompletedTask); } //Get the inputted value through the value provider var value = bindingContext.ValueProvider .GetValue(bindingContext.ModelName).ToString(); // if that value is null or whitespace, we returnnull if (string.IsNullOrWhiteSpace(value)) { bindingContext.Result = ModelBindingResult.Success(null); return(Task.CompletedTask); } //The value isn'tnull or whitespace //and the type of the modelis enumerable //Get the enumerable's type and a converter var elementType = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0]; var converter = TypeDescriptor.GetConverter(elementType); //Convert each itemin the value list to the enumerable type... var values = value.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries) .Select(x => converter.ConvertFromString(x.Trim())) .ToArray(); //return a succesful result, passinthemodel bindingContext.Result = ModelBindingResult.Success(bindingContext.Model); return(Task.CompletedTask); }
public Task BindModelAsync(ModelBindingContext bindingContext) { if (!bindingContext.ModelMetadata.IsEnumerableType) { bindingContext.Result = ModelBindingResult.Failed(); return(Task.CompletedTask); } var providedValue = bindingContext.ValueProvider .GetValue(bindingContext.ModelName) .ToString(); //If this is null, return to the controller as there is error handling for null; if (string.IsNullOrEmpty(providedValue)) { bindingContext.Result = ModelBindingResult.Success(null); return(Task.CompletedTask); } //Use refelction to get type of Model (Guid) var genericType = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0]; //Get a converter for generic type var converter = TypeDescriptor.GetConverter(genericType); //Remove empty entries, trim and create object array var objectArray = providedValue.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries) .Select(x => converter.ConvertFromString(x.Trim())) .ToArray(); //Copy the oject array to the guid array var guidArray = Array.CreateInstance(genericType, objectArray.Length); objectArray.CopyTo(guidArray, 0); //Bind the Guid array to the bindingContext bindingContext.Model = guidArray; bindingContext.Result = ModelBindingResult.Success(bindingContext.Model); return(Task.CompletedTask); }
public Task BindModelAsync(ModelBindingContext bindingContext) { // 只适用于IEnumerable类型 if (!bindingContext.ModelMetadata.IsEnumerableType) { bindingContext.Result = ModelBindingResult.Failed(); return(Task.CompletedTask); } // 取得输入的值 var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).ToString(); // 空就返回 if (string.IsNullOrWhiteSpace(value)) { bindingContext.Result = ModelBindingResult.Success(null); return(Task.CompletedTask); } // 取得IEnumerable的类型 var elementType = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0]; var converter = TypeDescriptor.GetConverter(elementType); // 把列表中的每项都转化为IEnumerable的类型 var values = value.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries) .Select(x => converter.ConvertFromString(x.Trim())) .ToArray(); // 创建该类型的数组, 把它设为Model的值 var typedValues = Array.CreateInstance(elementType, values.Length); values.CopyTo(typedValues, 0); bindingContext.Model = typedValues; // 成功, 把model传过去 bindingContext.Result = ModelBindingResult.Success(bindingContext.Model); return(Task.CompletedTask); }
public async Task BindModelAsync(ModelBindingContext bindingContext) { var typeName = ModelNames.CreatePropertyModelName(bindingContext.ModelName, nameof(Summary.SubtypeName)); var typeValue = bindingContext.ValueProvider.GetValue(typeName).FirstValue; var type = string.IsNullOrEmpty(typeValue) ? null : Type.GetType(typeValue.ToString(), true); // If the type is null, then the object is null (every instance must have a // SubtypeName). Fail to bind, in this case if (type == null) { bindingContext.Result = ModelBindingResult.Failed(); return; } // Otherwise, create a new metadata and binding context, // and recursively bind the subtype var modelMetadata = _providerContext.MetadataProvider.GetMetadataForType(type); var binder = _providerContext.CreateBinder(modelMetadata); var newBindingContext = DefaultModelBindingContext.CreateBindingContext( bindingContext.ActionContext, bindingContext.ValueProvider, modelMetadata, bindingInfo: null, bindingContext.ModelName); await binder.BindModelAsync(newBindingContext); bindingContext.Result = newBindingContext.Result; if (newBindingContext.Result.IsModelSet) { // Setting the ValidationState ensures properties on derived types are correctly bindingContext.ValidationState[newBindingContext.Result] = new ValidationStateEntry { Metadata = modelMetadata, }; } }
/// <summary> /// Creates an model bound array to makes an incoming collection enumerable /// </summary> /// <param name="bindingContext">non-model/non-type list</param> /// <returns>Model Bound Array dependent on value types</returns> public Task BindModelAsync(ModelBindingContext bindingContext) { //validate enumerable if (!bindingContext.ModelMetadata.IsEnumerableType) { bindingContext.Result = ModelBindingResult.Failed(); return(Task.CompletedTask); } //Get input value var inputValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).ToString(); //Validate not null or white space if (string.IsNullOrWhiteSpace(inputValue)) { bindingContext.Result = ModelBindingResult.Success(null); return(Task.CompletedTask); } //Get enumerable type and converter var elementType = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0]; var converter = TypeDescriptor.GetConverter(elementType); //convert each type in the list to it's enumerable type var values = inputValue.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries) .Select(v => converter.ConvertFromString(v.Trim())) .ToArray(); //Copy array into an array of the correct type var typedValues = Array.CreateInstance(elementType, values.Length); values.CopyTo(typedValues, 0); bindingContext.Model = typedValues; //return typed arrray bindingContext.Result = ModelBindingResult.Success(bindingContext.Model); return(Task.CompletedTask); }
public Task BindModelAsync(ModelBindingContext bindingContext) { // Trabajaremos con nuestro binder solo en caso de que el tipo sea un ienumerable if (!bindingContext.ModelMetadata.IsEnumerableType) { bindingContext.Result = ModelBindingResult.Failed(); return(Task.CompletedTask); } // Obtenemos el valor ingresado var value = bindingContext.ValueProvider .GetValue(bindingContext.ModelName).ToString(); if (string.IsNullOrWhiteSpace(value)) { bindingContext.Result = ModelBindingResult.Success(null); return(Task.CompletedTask); } // Convierto el tipo enumerable var elementType = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0]; var converter = TypeDescriptor.GetConverter(elementType); // Creo una lista de id's var values = value.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries) .Select(x => converter.ConvertFromString(x.Trim())) .ToArray(); // Creo un array y lo seteo en el model binding var typedValues = Array.CreateInstance(elementType, values.Length); values.CopyTo(typedValues, 0); bindingContext.Model = typedValues; // Returno Success y el modelo bindingContext.Result = ModelBindingResult.Success(bindingContext.Model); return(Task.CompletedTask); }
public async Task BindModelAsync(ModelBindingContext bindingContext) { var controlTypeModelName = ModelNames.CreatePropertyModelName(bindingContext.ModelName, "ControlType"); var controlTypeResult = bindingContext.ValueProvider.GetValue(controlTypeModelName); if (controlTypeResult == ValueProviderResult.None) { bindingContext.Result = ModelBindingResult.Failed(); return; } IModelBinder binder; if (!_binders.TryGetValue(controlTypeResult.FirstValue, out binder)) { bindingContext.Result = ModelBindingResult.Failed(); return; } // Now know the type exists in the assembly. var type = Type.GetType(controlTypeResult.FirstValue); var metadata = _metadataProvider.GetMetadataForType(type); ModelBindingResult result; using (bindingContext.EnterNestedScope( metadata, bindingContext.FieldName, bindingContext.ModelName, model: null)) { await binder.BindModelAsync(bindingContext); result = bindingContext.Result; } bindingContext.Result = result; }
public Task BindModelAsync(ModelBindingContext bindingContext) { var propertyValuePairs = GetPropertyValuePairs(bindingContext); if (propertyValuePairs == null) { bindingContext.Result = ModelBindingResult.Failed(); return(Task.CompletedTask); } if (bindingContext.ModelState.IsValid) { Delta <T> delta = null; if (bindingContext.ModelState.IsValid) { delta = new Delta <T>(_jsonPropertyMapper, propertyValuePairs); ValidateModel(bindingContext, propertyValuePairs, delta.Dto); } if (bindingContext.ModelState.IsValid) { bindingContext.Model = delta; bindingContext.Result = ModelBindingResult.Success(bindingContext.Model); } else { bindingContext.Result = ModelBindingResult.Failed(); } } else { bindingContext.Result = ModelBindingResult.Failed(); } return(Task.CompletedTask); }
public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } string fieldName = bindingContext.FieldName; var valueProviderResult = bindingContext.ValueProvider.GetValue(fieldName); if (valueProviderResult == ValueProviderResult.None) { return(Task.CompletedTask); } else { bindingContext.ModelState.SetModelValue(fieldName, valueProviderResult); } string value = valueProviderResult.FirstValue; if (string.IsNullOrEmpty(value)) { return(Task.CompletedTask); } try { object result = JsonConvert.DeserializeObject(value, bindingContext.ModelType); bindingContext.Result = ModelBindingResult.Success(result); } catch (JsonException) { bindingContext.Result = ModelBindingResult.Failed(); } return(Task.CompletedTask); }
public Task BindModelAsync(ModelBindingContext bindingContext) { if (!bindingContext.ModelMetadata.IsEnumerableType) { bindingContext.Result = ModelBindingResult.Failed(); return(Task.CompletedTask); } var providedValue = bindingContext .ValueProvider .GetValue(bindingContext.ModelName) .ToString(); if (string.IsNullOrEmpty(providedValue)) { bindingContext.Result = ModelBindingResult.Success(null); return(Task.CompletedTask); } var genericType = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0]; var converter = TypeDescriptor.GetConverter(genericType); var objectArray = providedValue.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries) .Select(x => converter.ConvertFromString(x.Trim())) .ToArray(); var guidArray = Array.CreateInstance(genericType, objectArray.Length); objectArray.CopyTo(guidArray, 0); bindingContext.Model = guidArray; bindingContext.Result = ModelBindingResult.Success(bindingContext.Model); return(Task.CompletedTask); }
public async Task BindModelAsync(ModelBindingContext bindingContext) { var contentType = bindingContext.ActionContext.HttpContext.Request.ContentType; BindingInfo bindingInfo = new BindingInfo(); if (contentType == "application/json") { } else if (contentType == "application/x-www-form-urlencoded") { bindingInfo.BindingSource = BindingSource.Form; } else { bindingContext.Result = ModelBindingResult.Failed(); } var binder = factory.CreateBinder(new ModelBinderFactoryContext { Metadata = bindingContext.ModelMetadata, BindingInfo = bindingInfo, }); await binder.BindModelAsync(bindingContext); }
private static IModelBinder CreateIntBinder() { return(new StubModelBinder(context => { var value = context.ValueProvider.GetValue(context.ModelName); if (value != ValueProviderResult.None) { object valueToConvert = null; if (value.Values.Count == 1) { valueToConvert = value.Values[0]; } else if (value.Values.Count > 1) { valueToConvert = value.Values.ToArray(); } var model = ModelBindingHelper.ConvertTo(valueToConvert, context.ModelType, value.Culture); return ModelBindingResult.Success(model); } return ModelBindingResult.Failed(); })); }
public async Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext.ModelType != typeof(StatementCollection)) { return; } try { var request = bindingContext.ActionContext.HttpContext.Request; var jsonModelReader = new JsonModelReader(request.Headers, request.Body); var statements = await jsonModelReader.ReadAs <StatementCollection>(); bindingContext.Result = ModelBindingResult.Success(statements); return; } catch (JsonModelReaderException ex) { bindingContext.ModelState.TryAddModelException <StatementCollection>(x => x, ex); bindingContext.Result = ModelBindingResult.Failed(); } }
public Task BindModelAsync(ModelBindingContext bindingContext) { var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueResult); var converter = TypeDescriptor.GetConverter(bindingContext.ModelType); try { var result = converter.ConvertFrom(valueResult.FirstValue); bindingContext.Result = ModelBindingResult.Success(result); } catch (ArgumentException) { bindingContext.Result = ModelBindingResult.Failed(); var errorSuppressBinderAttribute = (bindingContext.ModelMetadata as DefaultModelMetadata).Attributes.PropertyAttributes.FirstOrDefault(x => x.GetType() == typeof(SuppressArgumentExceptionAttribute)) as SuppressArgumentExceptionAttribute; bindingContext.ModelState.TryAddModelError( errorSuppressBinderAttribute.PropertyName, errorSuppressBinderAttribute.CustomErrorMessage); } return(Task.CompletedTask); }
public Task BindModelAsync(ModelBindingContext bindingContext) { if (!bindingContext.ModelMetadata.IsEnumerableType) { bindingContext.Result = ModelBindingResult.Failed(); return(Task.CompletedTask);; } var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).ToString(); if (string.IsNullOrWhiteSpace(value)) { bindingContext.Result = ModelBindingResult.Success(null); return(Task.CompletedTask); } var typedValues = GetTypedValues(bindingContext, value); bindingContext.Model = typedValues; bindingContext.Result = ModelBindingResult.Success(bindingContext.Model); return(Task.CompletedTask); }
public Task BindModelAsync(ModelBindingContext bindingContext) { EnsureArg.IsNotNull(bindingContext, nameof(bindingContext)); var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); if (valueProviderResult.Any() && !string.IsNullOrWhiteSpace(valueProviderResult.FirstValue)) { try { var result = PartialDateTime.Parse(valueProviderResult.FirstValue); bindingContext.Result = ModelBindingResult.Success(result); } catch (FormatException ex) { bindingContext.ModelState.AddModelError(bindingContext.ModelName, ex.Message); bindingContext.Result = ModelBindingResult.Failed(); } } return(Task.CompletedTask); }
public Task BindModelAsync(ModelBindingContext bindingContext) { string value = bindingContext.ValueProvider .GetValue(bindingContext.ModelName).FirstValue; if (bindingContext.ModelType == typeof(DateTime?) && String.IsNullOrEmpty(value)) { bindingContext.Result = ModelBindingResult.Success(null); return(Task.CompletedTask); } bindingContext.Result = DateTime.TryParseExact( value, DateTimeFormats, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var result) ? ModelBindingResult.Success(result) : ModelBindingResult.Failed(); return(Task.CompletedTask); }
public Task BindModelAsync(ModelBindingContext bindingContext) { // Binding only works on enumerable types if (!bindingContext.ModelMetadata.IsEnumerableType) { bindingContext.Result = ModelBindingResult.Failed(); return(Task.CompletedTask); } // Get inputted values var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).ToString(); // if value is null or whitespace, return null if (string.IsNullOrWhiteSpace(value)) { bindingContext.Result = ModelBindingResult.Success(null); return(Task.CompletedTask); } // converts string type to guid var elementType = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0]; var converter = TypeDescriptor.GetConverter(elementType); // convert value list into enumerable type var values = value.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select( x => converter.ConvertFromString(x.Trim())).ToArray(); // create array of model values var typedValues = Array.CreateInstance(elementType, values.Length); values.CopyTo(typedValues, 0); bindingContext.Model = typedValues; // return success bindingContext.Result = ModelBindingResult.Success(bindingContext.Model); return(Task.CompletedTask); }
public Task BindModelAsync(ModelBindingContext bindingContext) { //target only IEnumerable types if (!bindingContext.ModelMetadata.IsEnumerableType) { bindingContext.Result = ModelBindingResult.Failed(); return(Task.CompletedTask); } // Get the posted value to the controller action we are intercepting var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).ToString(); //if empty, just return success if (string.IsNullOrWhiteSpace(value)) { bindingContext.Result = ModelBindingResult.Success(null); return(Task.CompletedTask); } var elementType = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0]; var converter = TypeDescriptor.GetConverter(elementType); //convert each item in the value list to the enuerable type var values = value.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries) .Select(x => converter.ConvertFromString(x.Trim())) .ToArray(); //create array of the type and set it as the model value var typedValues = Array.CreateInstance(elementType, values.Length); values.CopyTo(typedValues, 0); bindingContext.Model = typedValues; //return successful result, passing in the model bindingContext.Result = ModelBindingResult.Success(bindingContext.Model); return(Task.CompletedTask); }
public async Task BindModelAsync(ModelBindingContext bindingContext) { if (!bindingContext.IsTopLevelObject) { return; } if (bindingContext.ModelType.Equals(typeof(AuthorizationRequest))) { var httpContext = bindingContext.HttpContext; var httpRequest = httpContext.Request; IEnumerable <KeyValuePair <string, StringValues> > source = null; if (httpRequest.Method.Equals("GET")) { source = httpRequest.Query; } else if (httpRequest.Method.Equals("POST")) { source = await httpRequest.ReadFormAsync(); } if (source == null) { bindingContext.Result = ModelBindingResult.Failed(); } else { var requestParameters = source.ToDictionary( kvp => kvp.Key, kvp => (string[])kvp.Value); var factory = httpContext.RequestServices.GetRequiredService <IAuthorizationRequestFactory>(); bindingContext.Result = ModelBindingResult.Success(await factory.CreateAuthorizationRequestAsync(requestParameters)); } } }
public async Task CollectionModelBinder_CreatesEmptyCollection_IfIsTopLevelObject( bool allowValidatingTopLevelNodes, bool isBindingRequired) { // Arrange var binder = new CollectionModelBinder <string>( new StubModelBinder(result: ModelBindingResult.Failed()), NullLoggerFactory.Instance, allowValidatingTopLevelNodes); var bindingContext = CreateContext(); bindingContext.IsTopLevelObject = true; // Lack of prefix and non-empty model name both ignored. bindingContext.ModelName = "modelName"; var metadataProvider = new TestModelMetadataProvider(); var parameter = typeof(CollectionModelBinderTest) .GetMethod(nameof(ActionWithListParameter), BindingFlags.Instance | BindingFlags.NonPublic) .GetParameters()[0]; metadataProvider .ForParameter(parameter) .BindingDetails(b => b.IsBindingRequired = isBindingRequired); bindingContext.ModelMetadata = metadataProvider.GetMetadataForParameter(parameter); bindingContext.ValueProvider = new TestValueProvider(new Dictionary <string, object>()); // Act await binder.BindModelAsync(bindingContext); // Assert Assert.Empty(Assert.IsType <List <string> >(bindingContext.Result.Model)); Assert.True(bindingContext.Result.IsModelSet); Assert.Equal(0, bindingContext.ModelState.ErrorCount); }
public Task BindModelAsync(ModelBindingContext bindingContext) { //This binder only works for IEnumerable Types if (!bindingContext.ModelMetadata.IsEnumerableType) { bindingContext.Result = ModelBindingResult.Failed(); return(Task.CompletedTask); } //getting the inputed value through the value provider var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).ToString(); //value is null or whitespace? return null if (string.IsNullOrWhiteSpace(value)) { bindingContext.Result = ModelBindingResult.Success(null); return(Task.CompletedTask); } //get the enumerable's type and converter //this converter help us to convert in this case string values to guids var elementType = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0]; var converter = TypeDescriptor.GetConverter(elementType); //convert each item in the value list to the enumerable type var values = value.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries) .Select(x => converter.ConvertFromString(x.Trim())).ToArray(); //create an array of that type and set it as the Model value var typedValues = Array.CreateInstance(elementType, values.Length); values.CopyTo(typedValues, 0); bindingContext.Model = typedValues; bindingContext.Result = ModelBindingResult.Success(bindingContext.Model); return(Task.CompletedTask); }
public Task BindModelAsync(ModelBindingContext bindingContext) { if (!typeof(uint160).GetTypeInfo().IsAssignableFrom(bindingContext.ModelType)) { return(Task.CompletedTask); } ValueProviderResult val = bindingContext.ValueProvider.GetValue( bindingContext.ModelName); if (val == null) { return(Task.CompletedTask); } string key = val.FirstValue as string; if (key == null) { bindingContext.Model = null; return(Task.CompletedTask); } try { var value = uint160.Parse(key); if (value.ToString().StartsWith(uint160.Zero.ToString())) { throw new FormatException("Invalid hash format"); } bindingContext.Result = ModelBindingResult.Success(value); } catch (FormatException) { bindingContext.Result = ModelBindingResult.Failed(); } return(Task.CompletedTask); }