本文整理汇总了C#中ModelValidationNode类的典型用法代码示例。如果您正苦于以下问题:C# ModelValidationNode类的具体用法?C# ModelValidationNode怎么用?C# ModelValidationNode使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ModelValidationNode类属于命名空间,在下文中一共展示了ModelValidationNode类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CombineWith
public void CombineWith() {
// Arrange
List<string> log = new List<string>();
ModelValidationNode[] allChildNodes = new ModelValidationNode[] {
new ModelValidationNode(GetModelMetadata(), "key1"),
new ModelValidationNode(GetModelMetadata(), "key2"),
new ModelValidationNode(GetModelMetadata(), "key3"),
};
ModelValidationNode parentNode1 = new ModelValidationNode(GetModelMetadata(), "parent1");
parentNode1.ChildNodes.Add(allChildNodes[0]);
parentNode1.Validating += delegate { log.Add("Validating parent1."); };
parentNode1.Validated += delegate { log.Add("Validated parent1."); };
ModelValidationNode parentNode2 = new ModelValidationNode(GetModelMetadata(), "parent2");
parentNode2.ChildNodes.Add(allChildNodes[1]);
parentNode2.ChildNodes.Add(allChildNodes[2]);
parentNode2.Validating += delegate { log.Add("Validating parent2."); };
parentNode2.Validated += delegate { log.Add("Validated parent2."); };
// Act
parentNode1.CombineWith(parentNode2);
parentNode1.Validate(new ControllerContext() { Controller = new EmptyController() });
// Assert
CollectionAssert.AreEqual(
new string[] { "Validating parent1.", "Validating parent2.", "Validated parent1.", "Validated parent2." },
log);
CollectionAssert.AreEqual(allChildNodes, parentNode1.ChildNodes.ToArray());
}
示例2: ModelBindingResult
/// <summary>
/// Creates a new <see cref="ModelBindingResult"/>.
/// </summary>
/// <param name="model">The model which was created by the <see cref="IModelBinder"/>.</param>
/// <param name="key">The key using which was used to attempt binding the model.</param>
/// <param name="isModelSet">A value that represents if the model has been set by the
/// <see cref="IModelBinder"/>.</param>
/// <param name="validationNode">A <see cref="ModelValidationNode"/> which captures the validation information.
/// </param>
public ModelBindingResult(object model, string key, bool isModelSet, ModelValidationNode validationNode)
{
Model = model;
Key = key;
IsModelSet = isModelSet;
ValidationNode = validationNode;
}
示例3: PropertiesAreSet
public void PropertiesAreSet() {
// Arrange
ModelMetadata metadata = GetModelMetadata();
string modelStateKey = "someKey";
// Act
ModelValidationNode node = new ModelValidationNode(metadata, modelStateKey);
// Assert
Assert.AreEqual(metadata, node.ModelMetadata);
Assert.AreEqual(modelStateKey, node.ModelStateKey);
Assert.IsNotNull(node.ChildNodes);
Assert.AreEqual(0, node.ChildNodes.Count);
}
示例4: ConstructorSetsCollectionInstance
public void ConstructorSetsCollectionInstance() {
// Arrange
ModelMetadata metadata = GetModelMetadata();
string modelStateKey = "someKey";
ModelValidationNode[] childNodes = new ModelValidationNode[] {
new ModelValidationNode(metadata, "someKey0"),
new ModelValidationNode(metadata, "someKey1")
};
// Act
ModelValidationNode node = new ModelValidationNode(metadata, modelStateKey, childNodes);
// Assert
CollectionAssert.AreEqual(childNodes, (ICollection)node.ChildNodes);
}
示例5: Validate_Ordering
public void Validate_Ordering() {
// Proper order of invocation:
// 1. OnValidating()
// 2. Child validators
// 3. This validator
// 4. OnValidated()
// Arrange
List<string> log = new List<string>();
LoggingDataErrorInfoModel model = new LoggingDataErrorInfoModel(log);
ModelMetadata modelMetadata = GetModelMetadata(model);
ControllerContext controllerContext = new ControllerContext() {
Controller = new EmptyController()
};
ModelValidationNode node = new ModelValidationNode(modelMetadata, "theKey");
ModelMetadata childMetadata = new EmptyModelMetadataProvider().GetMetadataForProperty(() => model, model.GetType(), "ValidStringProperty");
node.ChildNodes.Add(new ModelValidationNode(childMetadata, "theKey.ValidStringProperty"));
node.Validating += delegate {
log.Add("In OnValidating()");
};
node.Validated += delegate {
log.Add("In OnValidated()");
};
// Act
node.Validate(controllerContext);
// Assert
CollectionAssert.AreEqual(
new string[] { "In OnValidating()", "In IDataErrorInfo.get_Item('ValidStringProperty')", "In IDataErrorInfo.get_Error()", "In OnValidated()" },
log);
}
示例6: Validator_IfValidateAllPropertiesSet_WithChildNodes_DoesNotAutoExpand
public void Validator_IfValidateAllPropertiesSet_WithChildNodes_DoesNotAutoExpand()
{
// Arrange
var testValidationContext = GetModelValidationContext(
LonelyPerson,
typeof(Person));
var validationContext = testValidationContext.ModelValidationContext;
var validator = new DefaultObjectValidator(
testValidationContext.ExcludeFilters,
testValidationContext.ModelMetadataProvider);
var modelExplorer = testValidationContext.ModelValidationContext.ModelExplorer;
var topLevelValidationNode = new ModelValidationNode(
"person",
modelExplorer.Metadata,
modelExplorer.Model)
{
ValidateAllProperties = true
};
var propertyExplorer = modelExplorer.GetExplorerForProperty("Profession");
var childNode = new ModelValidationNode(
"person.Profession",
propertyExplorer.Metadata,
propertyExplorer.Model);
topLevelValidationNode.ChildNodes.Add(childNode);
// Act
validator.Validate(validationContext, topLevelValidationNode);
// Assert
var modelState = validationContext.ModelState;
Assert.False(modelState.IsValid);
// Since the model is invalid at property level there is no entry in the model state for top level node.
Assert.Single(modelState.Keys, k => k == "person.Profession");
Assert.Equal(1, modelState.Count);
}
示例7: Validate_ValidateAllProperties_AddsValidationErrors
public void Validate_ValidateAllProperties_AddsValidationErrors() {
// Arrange
ValidateAllPropertiesModel model = new ValidateAllPropertiesModel() {
RequiredString = null /* error */,
RangedInt = 0 /* error */,
ValidString = "dog"
};
ModelMetadata modelMetadata = GetModelMetadata(model);
ControllerContext controllerContext = new ControllerContext() {
Controller = new EmptyController()
};
ModelValidationNode node = new ModelValidationNode(modelMetadata, "theKey") {
ValidateAllProperties = true
};
controllerContext.Controller.ViewData.ModelState.AddModelError("theKey.RequiredString.Dummy", "existing Error Text");
// Act
node.Validate(controllerContext);
// Assert
Assert.IsNull(controllerContext.Controller.ViewData.ModelState["theKey.RequiredString"]);
Assert.AreEqual("existing Error Text", controllerContext.Controller.ViewData.ModelState["theKey.RequiredString.Dummy"].Errors[0].ErrorMessage);
Assert.AreEqual("The field RangedInt must be between 10 and 30.", controllerContext.Controller.ViewData.ModelState["theKey.RangedInt"].Errors[0].ErrorMessage);
Assert.IsNull(controllerContext.Controller.ViewData.ModelState["theKey.ValidString"]);
Assert.IsNull(controllerContext.Controller.ViewData.ModelState["theKey"]);
}
示例8: SetProperty_PropertyIsSettable_SetterThrows_RecordsError
public void SetProperty_PropertyIsSettable_SetterThrows_RecordsError()
{
// Arrange
Person model = new Person
{
DateOfBirth = new DateTime(1900, 1, 1)
};
ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext
{
ModelMetadata = GetMetadataForObject(model)
};
ModelMetadata propertyMetadata = bindingContext.ModelMetadata.Properties.Single(o => o.PropertyName == "DateOfDeath");
ModelValidationNode validationNode = new ModelValidationNode(propertyMetadata, "foo");
ComplexModelDtoResult dtoResult = new ComplexModelDtoResult(new DateTime(1800, 1, 1), validationNode);
TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();
// Act
testableBinder.SetPropertyPublic(null, bindingContext, propertyMetadata, dtoResult);
// Assert
Assert.Equal("Date of death can't be before date of birth." + Environment.NewLine
+ "Parameter name: value",
bindingContext.ModelState["foo"].Errors[0].Exception.Message);
}
示例9: SetProperty_SettingNonNullableValueTypeToNull_RequiredValidatorPresent_AddsModelError
public void SetProperty_SettingNonNullableValueTypeToNull_RequiredValidatorPresent_AddsModelError()
{
// Arrange
ControllerContext controllerContext = new ControllerContext
{
Controller = new EmptyController()
};
ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext
{
ModelMetadata = GetMetadataForObject(new Person()),
ModelName = "foo"
};
ModelMetadata propertyMetadata = bindingContext.ModelMetadata.Properties.Single(o => o.PropertyName == "ValueTypeRequired");
ModelValidationNode validationNode = new ModelValidationNode(propertyMetadata, "foo.ValueTypeRequired");
ComplexModelDtoResult dtoResult = new ComplexModelDtoResult(null /* model */, validationNode);
TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();
// Act
testableBinder.SetPropertyPublic(controllerContext, bindingContext, propertyMetadata, dtoResult);
// Assert
Assert.False(bindingContext.ModelState.IsValid);
Assert.Equal("Sample message", bindingContext.ModelState["foo.ValueTypeRequired"].Errors[0].ErrorMessage);
}
示例10: NullCheckFailedHandler_ModelStateValid_CallbackReturnsNull_DoesNothing
public void NullCheckFailedHandler_ModelStateValid_CallbackReturnsNull_DoesNothing()
{
// Arrange
ControllerContext controllerContext = new ControllerContext
{
Controller = new EmptyController()
};
ModelMetadata modelMetadata = GetMetadataForType(typeof(Person));
ModelValidationNode validationNode = new ModelValidationNode(modelMetadata, "foo");
ModelValidatedEventArgs e = new ModelValidatedEventArgs(controllerContext, null /* parentNode */);
// Act
ModelBinderErrorMessageProvider originalProvider = ModelBinderConfig.ValueRequiredErrorMessageProvider;
try
{
ModelBinderConfig.ValueRequiredErrorMessageProvider = delegate { return null; };
EventHandler<ModelValidatedEventArgs> handler = MutableObjectModelBinder.CreateNullCheckFailedHandler(controllerContext, modelMetadata, null /* incomingValue */);
handler(validationNode, e);
}
finally
{
ModelBinderConfig.ValueRequiredErrorMessageProvider = originalProvider;
}
// Assert
Assert.True(controllerContext.Controller.ViewData.ModelState.IsValid);
}
示例11: SetProperty_PropertyIsReadOnly_DoesNothing
public void SetProperty_PropertyIsReadOnly_DoesNothing()
{
// Arrange
ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext
{
ModelMetadata = GetMetadataForType(typeof(Person))
};
ModelMetadata propertyMetadata = bindingContext.ModelMetadata.Properties.Single(o => o.PropertyName == "NonUpdateableProperty");
ModelValidationNode validationNode = new ModelValidationNode(propertyMetadata, "foo");
ComplexModelDtoResult dtoResult = new ComplexModelDtoResult(null /* model */, validationNode);
TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();
// Act
testableBinder.SetPropertyPublic(null, bindingContext, propertyMetadata, dtoResult);
// Assert
// If didn't throw, success!
}
示例12: BindModel_UsesTheValidationNodeOnModelBindingResult_IfPresent
public async Task BindModel_UsesTheValidationNodeOnModelBindingResult_IfPresent()
{
// Arrange
var valueProvider = new SimpleHttpValueProvider();
ModelValidationNode validationNode = null;
var mockBinder = new Mock<IModelBinder>();
mockBinder
.Setup(o => o.BindModelAsync(It.IsAny<ModelBindingContext>()))
.Returns(
delegate (ModelBindingContext context)
{
validationNode = new ModelValidationNode("someName", context.ModelMetadata, 42);
return Task.FromResult(
new ModelBindingResult(42, "someName", isModelSet: true, validationNode: validationNode));
});
var binder = CreateCompositeBinder(mockBinder.Object);
var bindingContext = CreateBindingContext(binder, valueProvider, typeof(SimplePropertiesModel));
// Act
var result = await binder.BindModelAsync(bindingContext);
// Assert
Assert.NotNull(result);
Assert.True(result.IsModelSet);
Assert.Same(validationNode, result.ValidationNode);
}
示例13: NullCheckFailedHandler_ModelStateAlreadyInvalid_DoesNothing
public void NullCheckFailedHandler_ModelStateAlreadyInvalid_DoesNothing()
{
// Arrange
ControllerContext controllerContext = new ControllerContext
{
Controller = new EmptyController()
};
controllerContext.Controller.ViewData.ModelState.AddModelError("foo.bar", "Some existing error.");
ModelMetadata modelMetadata = GetMetadataForType(typeof(Person));
ModelValidationNode validationNode = new ModelValidationNode(modelMetadata, "foo");
ModelValidatedEventArgs e = new ModelValidatedEventArgs(controllerContext, null /* parentNode */);
// Act
EventHandler<ModelValidatedEventArgs> handler = MutableObjectModelBinder.CreateNullCheckFailedHandler(controllerContext, modelMetadata, null /* incomingValue */);
handler(validationNode, e);
// Assert
Assert.False(controllerContext.Controller.ViewData.ModelState.ContainsKey("foo"));
}
示例14: CombineWith_OtherNodeIsSuppressed_DoesNothing
public void CombineWith_OtherNodeIsSuppressed_DoesNothing()
{
// Arrange
List<string> log = new List<string>();
ModelValidationNode[] allChildNodes = new[]
{
new ModelValidationNode(GetModelMetadata(), "key1"),
new ModelValidationNode(GetModelMetadata(), "key2"),
new ModelValidationNode(GetModelMetadata(), "key3"),
};
ModelValidationNode[] expectedChildNodes = new[]
{
allChildNodes[0]
};
ModelValidationNode parentNode1 = new ModelValidationNode(GetModelMetadata(), "parent1");
parentNode1.ChildNodes.Add(allChildNodes[0]);
parentNode1.Validating += delegate { log.Add("Validating parent1."); };
parentNode1.Validated += delegate { log.Add("Validated parent1."); };
ModelValidationNode parentNode2 = new ModelValidationNode(GetModelMetadata(), "parent2");
parentNode2.ChildNodes.Add(allChildNodes[1]);
parentNode2.ChildNodes.Add(allChildNodes[2]);
parentNode2.Validating += delegate { log.Add("Validating parent2."); };
parentNode2.Validated += delegate { log.Add("Validated parent2."); };
parentNode2.SuppressValidation = true;
// Act
parentNode1.CombineWith(parentNode2);
parentNode1.Validate(new ControllerContext { Controller = new EmptyController() });
// Assert
Assert.Equal(new[] { "Validating parent1.", "Validated parent1." }, log.ToArray());
Assert.Equal(expectedChildNodes, parentNode1.ChildNodes.ToArray());
}
示例15: ControllerContext
public void SetProperty_SettingNullableTypeToNull_RequiredValidatorNotPresent_PropertySetterThrows_AddsRequiredMessageString() {
// Arrange
ControllerContext controllerContext = new ControllerContext() {
Controller = new EmptyController()
};
ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext() {
ModelMetadata = GetMetadataForObject(new ModelWhosePropertySetterThrows()),
ModelName = "foo"
};
ModelMetadata propertyMetadata = bindingContext.ModelMetadata.Properties.Single(o => o.PropertyName == "NameNoAttribute");
ModelValidationNode validationNode = new ModelValidationNode(propertyMetadata, "foo.NameNoAttribute");
ComplexModelDtoResult dtoResult = new ComplexModelDtoResult(null /* model */, validationNode);
TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();
// Act
testableBinder.SetPropertyPublic(controllerContext, bindingContext, propertyMetadata, dtoResult);
// Assert
Assert.IsFalse(bindingContext.ModelState.IsValid, "ModelState should've been marked invalid.");
Assert.AreEqual(1, bindingContext.ModelState["foo.NameNoAttribute"].Errors.Count);
Assert.AreEqual(@"This is a different exception.
Parameter name: value", bindingContext.ModelState["foo.NameNoAttribute"].Errors[0].Exception.Message);
}