public StubModelBinder(ModelBindingResult? result) { _callback = context => { context.Result = result; return TaskCache.CompletedTask; }; }
public async Task BindModelAsync_NoValue() { ModelMetadata metadata = new EmptyModelMetadataProvider().GetMetadataForType(typeof(String)); context.ValueProvider.GetValue(context.ModelName).Returns(ValueProviderResult.None); context.ModelMetadata = metadata; await binder.BindModelAsync(context); ModelBindingResult expected = new ModelBindingResult(); ModelBindingResult actual = context.Result; Assert.Equal(expected, actual); }
public void Constructor_SetsProperties() { // Arrange // Act var result = new ModelBindingResult( "some string", isModelSet: true, key: "someName"); // Assert Assert.Equal("some string", result.Model); Assert.True(result.IsModelSet); Assert.Equal("someName", result.Key); }
public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } if (bindingContext.ModelType != typeof(MyType)) { return(Task.CompletedTask); } string modelName = string.IsNullOrEmpty(bindingContext.BinderModelName) ? bindingContext.ModelName : bindingContext.BinderModelName; ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(modelName); if (valueProviderResult == ValueProviderResult.None) { return(Task.CompletedTask); } bindingContext.ModelState.SetModelValue(modelName, valueProviderResult); string valueToBind = valueProviderResult.FirstValue; if (valueToBind == null /* or not valid somehow*/) { return(Task.CompletedTask); } MyType value = ParseMyTypeFromJsonString(valueToBind); bindingContext.Result = ModelBindingResult.Success(value); return(Task.CompletedTask); }
public Task BindModelAsync(ModelBindingContext bindingContext) { // в случае ошибки возвращаем исключение if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } // с помощью поставщика значений получаем данные из запроса var datePartValues = bindingContext.ValueProvider.GetValue("Date"); var timePartValues = bindingContext.ValueProvider.GetValue("Time"); // если не найдено значений с данными ключами, вызываем привязчик модели по умолчанию if (datePartValues == ValueProviderResult.None || timePartValues == ValueProviderResult.None) { return(fallbackBinder.BindModelAsync(bindingContext)); } // получаем значения string date = datePartValues.FirstValue; string time = timePartValues.FirstValue; // Парсим дату и время DateTime.TryParse(date, out var parsedDateValue); DateTime.TryParse(time, out var parsedTimeValue); // Объединяем полученные значения в один объект DateTime var result = new DateTime(parsedDateValue.Year, parsedDateValue.Month, parsedDateValue.Day, parsedTimeValue.Hour, parsedTimeValue.Minute, parsedTimeValue.Second); // устанавливаем результат привязки bindingContext.Result = ModelBindingResult.Success(result); return(Task.CompletedTask); }
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 enumerable. //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 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 a successful result, passing in 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 ?? networkProvider.DefaultNetwork.CryptoCode); 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); }
public Task BindModelAsync(ModelBindingContext bindingContext) { var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); if (valueProviderResult != ValueProviderResult.None) { bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult); var valueAsString = "01/" + valueProviderResult.FirstValue; // valueAsString will have a string value of your date, e.g. '31/12/2017' //var dateTime = DateTime.ParseExact(valueAsString, "dd/MM/yyyy", CultureInfo.InvariantCulture); DateTime dateTime; if (DateTime.TryParseExact(valueAsString, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime)) { bindingContext.Result = ModelBindingResult.Success(dateTime); } return(Task.CompletedTask); } 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); }
/// <inheritdoc /> public async Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } object model; var request = bindingContext.HttpContext.Request; if (request.HasFormContentType) { var form = await request.ReadFormAsync(); model = form; } else { model = new EmptyFormCollection(); } bindingContext.Result = ModelBindingResult.Success(model); }
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 BindSimpleCollection_SubBindingSucceeds() { // Arrange var culture = new CultureInfo("fr-FR"); var bindingContext = GetModelBindingContext(new SimpleValueProvider()); Mock.Get <IModelBinder>(bindingContext.OperationBindingContext.ModelBinder) .Setup(o => o.BindModelAsync(It.IsAny <ModelBindingContext>())) .Returns((ModelBindingContext mbc) => { Assert.Equal("someName", mbc.ModelName); return(ModelBindingResult.SuccessAsync(mbc.ModelName, 42)); }); var modelBinder = new CollectionModelBinder <int>(); // Act var boundCollection = await modelBinder.BindSimpleCollection( bindingContext, new ValueProviderResult(new string[] { "0" })); // Assert Assert.Equal(new[] { 42 }, boundCollection.Model.ToArray()); }
public Task BindModelAsync(ModelBindingContext bindingContext) { var propertyName = bindingContext.ModelName; var value = bindingContext.ValueProvider.GetValue(propertyName); if (value == ValueProviderResult.None) { return(Task.CompletedTask); } else { try { var deserializedValue = JsonConvert.DeserializeObject <T>(value.FirstValue); bindingContext.Result = ModelBindingResult.Success(deserializedValue); } catch { bindingContext.ModelState.TryAddModelError(propertyName, "The given value is not of the correct type"); } 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) { 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); }
/// <inheritdoc/> public async Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } using (var reader = new StreamReader(bindingContext.HttpContext.Request.Body)) { var body = await reader.ReadToEndAsync().ConfigureAwait(continueOnCapturedContext: false); // Do something var value = JsonConvert.DeserializeObject(body, bindingContext.ModelType, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, ContractResolver = new CamelCasePropertyNamesContractResolver(), ReferenceLoopHandling = ReferenceLoopHandling.Serialize, PreserveReferencesHandling = PreserveReferencesHandling.Objects, }); bindingContext.Result = ModelBindingResult.Success(value); } }
public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } if (bindingContext.HttpContext.Request.QueryString.HasValue) { var queryParameters = bindingContext.HttpContext.Request.Query.ToDictionary(pair => pair.Key, pair => pair.Value.ToString()); bindingContext.Model = _objectConverter.ToObject <T>(queryParameters); } else { bindingContext.Model = new T(); } bindingContext.Result = ModelBindingResult.Success(bindingContext.Model); // This should be true otherwise the model will be null. return(Task.CompletedTask); }
public async Task BindModelAsync(ModelBindingContext bindingContext) { await simpleTypeModelBinder.BindModelAsync(bindingContext); if (!bindingContext.Result.IsModelSet) { return; } if (type == typeof(DateTime)) { var dateTime = (DateTime)bindingContext.Result.Model; bindingContext.Result = ModelBindingResult.Success(Clock.Normalize(dateTime)); } else { var dateTime = (DateTime?)bindingContext.Result.Model; if (dateTime != null) { bindingContext.Result = ModelBindingResult.Success(Clock.Normalize(dateTime.Value)); } } }
public Task BindModelAsync(ModelBindingContext bindingContext) { var valueProviderResult = bindingContext .ValueProvider .GetValue(bindingContext.ModelName); // use the norweigan culture // see https://stackoverflow.com/a/8341847/1108891 var cultureInfo = new CultureInfo("no"); decimal.TryParse( valueProviderResult.FirstValue, NumberStyles.Currency, cultureInfo, out var model); bindingContext .ModelState .SetModelValue(bindingContext.ModelName, valueProviderResult); bindingContext.Result = ModelBindingResult.Success(model); return(Task.CompletedTask); }
public Task BindModelAsync(ModelBindingContext bindingContext) { var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); if (valueProviderResult == ValueProviderResult.None) { return Task.CompletedTask; } var value = valueProviderResult.FirstValue; if (value == null) { bindingContext.ModelState.SetModelValue(bindingContext.ModelName, value, value); bindingContext.Result = ModelBindingResult.Success(value); return Task.CompletedTask; } if (DateTime.TryParse(value, valueProviderResult.Culture, DateTimeStyles.None, out var dateTime)) { bindingContext.ModelState.SetModelValue(bindingContext.ModelName, value.Trim(), value.Trim()); bindingContext.Result = ModelBindingResult.Success(dateTime); } return Task.CompletedTask; }
public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } var idValue = bindingContext.ValueProvider.GetValue("Id"); var nameValue = bindingContext.ValueProvider.GetValue("Name"); int.TryParse(idValue.FirstValue, out int id); var result = new CustomModelBindingTest { Id = id, Name = "nameValue.FirstValue" }; bindingContext.Result = ModelBindingResult.Success(result); return(Task.CompletedTask); }
public Task BindModelAsync(ModelBindingContext bindingContext) { if (!typeof(Script).GetTypeInfo().IsAssignableFrom(bindingContext.ModelType)) { return(Task.CompletedTask); } ValueProviderResult val = bindingContext.ValueProvider.GetValue( bindingContext.ModelName); string key = val.FirstValue as string; if (key == null) { bindingContext.Model = null; return(Task.CompletedTask); } var value = new Script(Encoders.Hex.DecodeData(key)); bindingContext.Result = ModelBindingResult.Success(value); return(Task.CompletedTask); }
public Task BindModelAsync(ModelBindingContext bindingContext) { var modelName = bindingContext.ModelName; var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName); if (valueProviderResult == ValueProviderResult.None) { return(Task.CompletedTask); } bindingContext.ModelState.SetModelValue(modelName, valueProviderResult); var value = valueProviderResult.FirstValue; if (string.IsNullOrEmpty(value)) { return(Task.CompletedTask); } var sortings = SortingAttribute.GetSortings(value); bindingContext.Result = ModelBindingResult.Success(sortings); return(Task.CompletedTask); }
public async Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } var jsonString = await ReadBodyAsString(bindingContext); var genericArguments = bindingContext .ModelType .GetTypeInfo() .GetGenericArguments(); if (genericArguments.Count() != 1) { throw new InvalidOperationException($"JsonDeltaModelBinder can only act on a type of IDelta<TModel>. Incorrect number of generic arguments found on type '{ bindingContext.ModelType.FullName }' ({ genericArguments.Count() })"); } var deltaType = typeof(JsonDelta <>).MakeGenericType(genericArguments.Single()); var result = Activator.CreateInstance(deltaType, new object[] { jsonString, _jsonSerializerSettings }); bindingContext.Result = ModelBindingResult.Success(result); }
public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); if (valueProviderResult != ValueProviderResult.None) { bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult); var valueAsString = valueProviderResult.FirstValue; if (decimal.TryParse(valueAsString.Replace(" ", "").Replace(".", ","), out var result)) { bindingContext.Result = ModelBindingResult.Success(result); return(Task.CompletedTask); } } return(_baseBinder.BindModelAsync(bindingContext)); }
/// <summary> /// Creates the model from the request and binds it to the context /// </summary> /// <param name="bindingContext"></param> /// <returns></returns> public async Task BindModelAsync(ModelBindingContext bindingContext) { var model = await _modelBinderHelper.BindModelFromMultipartRequestAsync <MediaItemSave>(_jsonSerializer, _hostingEnvironment, bindingContext); if (model == null) { return; } model.PersistedContent = ContentControllerBase.IsCreatingAction(model.Action) ? CreateNew(model) : GetExisting(model) !; //create the dto from the persisted model if (model.PersistedContent != null) { model.PropertyCollectionDto = _umbracoMapper.Map <IMedia, ContentPropertyCollectionDto>(model.PersistedContent); //now map all of the saved values to the dto _modelBinderHelper.MapPropertyValuesFromSaved(model, model.PropertyCollectionDto); } model.Name = model.Name?.Trim(); bindingContext.Result = ModelBindingResult.Success(model); }
/// <summary> /// /// </summary> public Task BindModelAsync(ModelBindingContext bindingContext) { ValueProviderResult valueProvider = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); if (valueProvider.FirstValue == null) { bindingContext.Model = null; return(Task.CompletedTask); } if (double.TryParse(valueProvider.FirstValue, NumberStyles.Any, CultureInfo.CurrentCulture, out double parsedValue)) { bindingContext.Model = parsedValue; bindingContext.Result = ModelBindingResult.Success(bindingContext.Model); } else { bindingContext.Model = null; } return(Task.CompletedTask); }
public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); if (valueProviderResult != ValueProviderResult.None) { bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult); var valueAsString = valueProviderResult.FirstValue; decimal result; // Use invariant culture if (decimal.TryParse(valueAsString, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out result)) { bindingContext.Result = ModelBindingResult.Success(result); return(Task.CompletedTask); } } // If we haven't handled it, then we'll let the base SimpleTypeModelBinder handle it return(_baseBinder.BindModelAsync(bindingContext)); }
public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } var form = bindingContext.HttpContext.Request.Form; var result = new SubmissionModel.Add { LanguageId = Convert.ToInt32(form["languageId"]), SourceCode = form["sourceCode"], Inputs = form.Files.GetFiles("inputs"), Outputs = form.Files.GetFiles("outputs"), Checker = form["checker"], CheckerType = (CheckerEnum)Convert.ToInt32(form["checkerType"]), }; bindingContext.Result = ModelBindingResult.Success(result); return(Task.CompletedTask); }
public async Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } ContentItemSave?model = await _modelBinderHelper.BindModelFromMultipartRequestAsync <ContentItemSave>(_jsonSerializer, _hostingEnvironment, bindingContext); if (model is null) { return; } IContent?persistedContent = ContentControllerBase.IsCreatingAction(model.Action) ? CreateNew(model) : GetExisting(model); BindModel(model, persistedContent !, _modelBinderHelper, _umbracoMapper); bindingContext.Result = ModelBindingResult.Success(model); }
public static async Task BindModelAsync_ReturnsSuccessWithOrder( [Frozen] ApplicationDbContext dbContext, [Frozen] CallOffId callOffId, Order order, Mock <IValueProvider> valueProviderMock, Mock <ModelBindingContext> contextMock, OrderModelBinder modelBinder) { dbContext.Order.Add(order); await dbContext.SaveChangesAsync(); contextMock.SetupAllProperties(); contextMock.Setup(c => c.ValueProvider).Returns(valueProviderMock.Object); valueProviderMock .Setup(v => v.GetValue(It.IsAny <string>())) .Returns(new ValueProviderResult(new StringValues(callOffId.ToString()))); var context = contextMock.Object; await modelBinder.BindModelAsync(context); context.Result.Should().Be(ModelBindingResult.Success(order)); }
public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } var(servedType, declaredFor) = GetStrategyTypes(bindingContext, typeof(IBehaviors <>)); object behaviors = behaviorsFactory.GetBehaviors(servedType, declaredFor); // Everything worked out; we have behaviors! // Hand back our resulting object, and we're done. bindingContext.Result = ModelBindingResult.Success(behaviors); // Don't validate our behaviors object - nothing on it is user input. bindingContext.ValidationState[behaviors] = new ValidationStateEntry() { SuppressValidation = true }; return(Task.CompletedTask); }
/// <summary> /// Updates a property in the current model /// </summary> /// <param name="bindingContext">Model binding context</param> /// <param name="modelName">The model name</param> /// <param name="propertyMetadata">The model metadata for the property to set</param> /// <param name="bindingResult">The binding result for the property's new value</param> protected override void SetProperty(ModelBindingContext bindingContext, string modelName, ModelMetadata propertyMetadata, ModelBindingResult bindingResult) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } //trim property string values for nop models var valueAsString = bindingResult.Model as string; if (bindingContext.Model is BaseGSModel && !string.IsNullOrEmpty(valueAsString)) { //excluding properties with [NoTrim] attribute var noTrim = (propertyMetadata as DefaultModelMetadata)?.Attributes?.Attributes?.OfType <NoTrimAttribute>().Any(); if (!noTrim.HasValue || !noTrim.Value) { bindingResult = ModelBindingResult.Success(valueAsString.Trim()); } } base.SetProperty(bindingContext, modelName, propertyMetadata, bindingResult); }
public async Task TryBindStrongModel_InnerBinderReturnsNotNull_ReturnsInnerBinderResult( object model, bool isModelSet) { // Arrange var innerResult = new ModelBindingResult(model, key: string.Empty, isModelSet: isModelSet); var innerBinder = new Mock<IModelBinder>(); innerBinder .Setup(o => o.BindModelAsync(It.IsAny<ModelBindingContext>())) .Returns((ModelBindingContext context) => { Assert.Equal("someName.key", context.ModelName); return Task.FromResult(innerResult); }); var bindingContext = GetBindingContext(new SimpleHttpValueProvider(), innerBinder.Object); var binder = new KeyValuePairModelBinder<int, string>(); var modelValidationNodeList = new List<ModelValidationNode>(); // Act var result = await binder.TryBindStrongModel<int>(bindingContext, "key", modelValidationNodeList); // Assert Assert.Same(innerResult, result); Assert.Empty(bindingContext.ModelState); }
/// <summary> /// Updates a property in the current <see cref="ModelBindingContext.Model"/>. /// </summary> /// <param name="bindingContext">The <see cref="ModelBindingContext"/>.</param> /// <param name="propertyMetadata">The <see cref="ModelMetadata"/> for the property to set.</param> /// <param name="result">The <see cref="ModelBindingResult"/> for the property's new value.</param> protected virtual void SetProperty( ModelBindingContext bindingContext, ModelMetadata propertyMetadata, ModelBindingResult result) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } if (propertyMetadata == null) { throw new ArgumentNullException(nameof(propertyMetadata)); } if (!result.IsModelSet) { // If we don't have a value, don't set it on the model and trounce a pre-initialized value. return; } if (propertyMetadata.IsReadOnly) { // The property should have already been set when we called BindPropertyAsync, so there's // nothing to do here. return; } var value = result.Model; try { propertyMetadata.PropertySetter(bindingContext.Model, value); } catch (Exception exception) { AddModelError(exception, bindingContext, result); } }
private static void AddModelError( Exception exception, ModelBindingContext bindingContext, ModelBindingResult result) { var targetInvocationException = exception as TargetInvocationException; if (targetInvocationException != null && targetInvocationException.InnerException != null) { exception = targetInvocationException.InnerException; } // Do not add an error message if a binding error has already occurred for this property. var modelState = bindingContext.ModelState; var modelStateKey = result.Key; var validationState = modelState.GetFieldValidationState(modelStateKey); if (validationState == ModelValidationState.Unvalidated) { modelState.AddModelError(modelStateKey, exception, bindingContext.ModelMetadata); } }
protected override void SetProperty( ModelBindingContext bindingContext, string modelName, ModelMetadata propertyMetadata, ModelBindingResult result) { SetPropertyPublic(bindingContext, modelName, propertyMetadata, result); }
public virtual void SetPropertyPublic( ModelBindingContext bindingContext, string modelName, ModelMetadata propertyMetadata, ModelBindingResult result) { base.SetProperty(bindingContext, modelName, propertyMetadata, result); }
/// <inheritdoc /> public override NestedScope EnterNestedScope() { _stack.Push(_state); Result = default(ModelBindingResult); return new NestedScope(this); }