本文整理汇总了C#中TestModelMetadataProvider.GetMetadataForProperty方法的典型用法代码示例。如果您正苦于以下问题:C# TestModelMetadataProvider.GetMetadataForProperty方法的具体用法?C# TestModelMetadataProvider.GetMetadataForProperty怎么用?C# TestModelMetadataProvider.GetMetadataForProperty使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类TestModelMetadataProvider
的用法示例。
在下文中一共展示了TestModelMetadataProvider.GetMetadataForProperty方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Create_ForModelMetadataReadOnly_ReturnsNull
public void Create_ForModelMetadataReadOnly_ReturnsNull()
{
// Arrange
var metadataProvider = new TestModelMetadataProvider();
metadataProvider.ForProperty(
typeof(ModelWithIntArrayProperty),
nameof(ModelWithIntArrayProperty.ArrayProperty)).BindingDetails(bd => bd.IsReadOnly = true);
var modelMetadata = metadataProvider.GetMetadataForProperty(
typeof(ModelWithIntArrayProperty),
nameof(ModelWithIntArrayProperty.ArrayProperty));
var provider = new ArrayModelBinderProvider();
var context = new TestModelBinderProviderContext(typeof(int[]));
context.OnCreatingBinder((m) =>
{
// Expect to be called with the element type to create a binder for elements.
Assert.Equal(typeof(int), m.ModelType);
return Mock.Of<IModelBinder>();
});
// Act
var result = provider.GetBinder(context);
// Assert
Assert.IsType<ArrayModelBinder<int>>(result);
}
示例2: BindModelAsync_ValueProviderContainPrefix_Succeeds
public async Task BindModelAsync_ValueProviderContainPrefix_Succeeds()
{
// Arrange
var valueProvider = new SimpleValueProvider
{
{ "someName[0]", "42" },
{ "someName[1]", "84" },
};
var bindingContext = GetBindingContext(valueProvider);
var metadataProvider = new TestModelMetadataProvider();
bindingContext.ModelMetadata = metadataProvider.GetMetadataForProperty(
typeof(ModelWithIntArrayProperty),
nameof(ModelWithIntArrayProperty.ArrayProperty));
var binder = new ArrayModelBinder<int>(new SimpleTypeModelBinder(typeof(int)));
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.True(bindingContext.Result.IsModelSet);
var array = Assert.IsType<int[]>(bindingContext.Result.Model);
Assert.Equal(new[] { 42, 84 }, array);
}
示例3: AddValidation_CorrectValidationTypeAndOverriddenErrorMessage
public void AddValidation_CorrectValidationTypeAndOverriddenErrorMessage()
{
// Arrange
var expectedMessage = "Error message about 'DisplayId' from override.";
var provider = new TestModelMetadataProvider();
provider
.ForProperty(typeof(TypeWithNumericProperty), nameof(TypeWithNumericProperty.Id))
.BindingDetails(d => d.ModelBindingMessageProvider.ValueMustBeANumberAccessor =
name => $"Error message about '{ name }' from override.");
var metadata = provider.GetMetadataForProperty(
typeof(TypeWithNumericProperty),
nameof(TypeWithNumericProperty.Id));
var adapter = new NumericClientModelValidator();
var actionContext = new ActionContext();
var context = new ClientModelValidationContext(actionContext, metadata, provider, new AttributeDictionary());
// Act
adapter.AddValidation(context);
// Assert
Assert.Collection(
context.Attributes,
kvp => { Assert.Equal("data-val", kvp.Key); Assert.Equal("true", kvp.Value); },
kvp => { Assert.Equal("data-val-number", kvp.Key); Assert.Equal(expectedMessage, kvp.Value); });
}
示例4: ArrayModelBinder_DoesNotCreateCollection_IfNotIsTopLevelObject
public async Task ArrayModelBinder_DoesNotCreateCollection_IfNotIsTopLevelObject(string prefix)
{
// Arrange
var binder = new ArrayModelBinder<string>(new SimpleTypeModelBinder(typeof(string)));
var bindingContext = CreateContext();
bindingContext.ModelName = ModelNames.CreatePropertyModelName(prefix, "ArrayProperty");
var metadataProvider = new TestModelMetadataProvider();
bindingContext.ModelMetadata = metadataProvider.GetMetadataForProperty(
typeof(ModelWithArrayProperty),
nameof(ModelWithArrayProperty.ArrayProperty));
bindingContext.ValueProvider = new TestValueProvider(new Dictionary<string, object>());
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.False(bindingContext.Result.IsModelSet);
}
示例5: AddModelError_ForNotModelsExpression_AddsExpectedException
public void AddModelError_ForNotModelsExpression_AddsExpectedException()
{
// Arrange
var dictionary = new ModelStateDictionary();
var variable = "Test";
var exception = new Exception();
var provider = new TestModelMetadataProvider();
var metadata = provider.GetMetadataForProperty(typeof(string), nameof(string.Length));
// Act
dictionary.AddModelError<TestModel>(model => variable, exception, metadata);
// Assert
var modelState = Assert.Single(dictionary);
var modelError = Assert.Single(modelState.Value.Errors);
Assert.Equal("variable", modelState.Key);
Assert.Same(exception, modelError.Exception);
}
示例6: GetModelBindingContext
private static DefaultModelBindingContext GetModelBindingContext(
bool isReadOnly,
IDictionary<string, string> values = null)
{
var metadataProvider = new TestModelMetadataProvider();
metadataProvider
.ForProperty<ModelWithIDictionaryProperty>(nameof(ModelWithIDictionaryProperty.DictionaryProperty))
.BindingDetails(bd => bd.IsReadOnly = isReadOnly);
var metadata = metadataProvider.GetMetadataForProperty(
typeof(ModelWithIDictionaryProperty),
nameof(ModelWithIDictionaryProperty.DictionaryProperty));
var valueProvider = new SimpleValueProvider();
foreach (var kvp in values)
{
valueProvider.Add(kvp.Key, string.Empty);
}
var bindingContext = new DefaultModelBindingContext
{
ModelMetadata = metadata,
ModelName = "someName",
ModelState = new ModelStateDictionary(),
ValueProvider = valueProvider,
ValidationState = new ValidationStateDictionary(),
};
return bindingContext;
}
示例7: BindModel_FallsBackToBindingValues_WithCustomDictionary
public async Task BindModel_FallsBackToBindingValues_WithCustomDictionary(
string modelName,
string keyFormat,
IDictionary<string, string> dictionary)
{
// Arrange
var expectedDictionary = new SortedDictionary<string, string>(dictionary);
var binder = new DictionaryModelBinder<string, string>(
new SimpleTypeModelBinder(typeof(string)),
new SimpleTypeModelBinder(typeof(string)));
var bindingContext = CreateContext();
bindingContext.ModelName = modelName;
bindingContext.ValueProvider = CreateEnumerableValueProvider(keyFormat, dictionary);
bindingContext.FieldName = bindingContext.ModelName;
var metadataProvider = new TestModelMetadataProvider();
bindingContext.ModelMetadata = metadataProvider.GetMetadataForProperty(
typeof(ModelWithDictionaryProperties),
nameof(ModelWithDictionaryProperties.CustomDictionaryProperty));
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.True(bindingContext.Result.IsModelSet);
var resultDictionary = Assert.IsAssignableFrom<SortedDictionary<string, string>>(bindingContext.Result.Model);
Assert.Equal(expectedDictionary, resultDictionary);
}
示例8: BindModel_FallsBackToBindingValues_WithComplexValues
public async Task BindModel_FallsBackToBindingValues_WithComplexValues()
{
// Arrange
var dictionary = new Dictionary<int, ModelWithProperties>
{
{ 23, new ModelWithProperties { Id = 43, Name = "Wilma" } },
{ 27, new ModelWithProperties { Id = 98, Name = "Fred" } },
};
var stringDictionary = new Dictionary<string, string>
{
{ "prefix[23].Id", "43" },
{ "prefix[23].Name", "Wilma" },
{ "prefix[27].Id", "98" },
{ "prefix[27].Name", "Fred" },
};
var bindingContext = CreateContext();
bindingContext.ModelName = "prefix";
bindingContext.ValueProvider = CreateEnumerableValueProvider("{0}", stringDictionary);
bindingContext.FieldName = bindingContext.ModelName;
var metadataProvider = new TestModelMetadataProvider();
bindingContext.ModelMetadata = metadataProvider.GetMetadataForProperty(
typeof(ModelWithDictionaryProperties),
nameof(ModelWithDictionaryProperties.DictionaryWithComplexValuesProperty));
var valueMetadata = metadataProvider.GetMetadataForType(typeof(ModelWithProperties));
var binder = new DictionaryModelBinder<int, ModelWithProperties>(
new SimpleTypeModelBinder(typeof(int)),
new ComplexTypeModelBinder(new Dictionary<ModelMetadata, IModelBinder>()
{
{ valueMetadata.Properties["Id"], new SimpleTypeModelBinder(typeof(int)) },
{ valueMetadata.Properties["Name"], new SimpleTypeModelBinder(typeof(string)) },
}));
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.True(bindingContext.Result.IsModelSet);
var resultDictionary = Assert.IsAssignableFrom<IDictionary<int, ModelWithProperties>>(bindingContext.Result.Model);
Assert.Equal(dictionary, resultDictionary);
// This requires a non-default IValidationStrategy
Assert.Contains(bindingContext.Result.Model, bindingContext.ValidationState.Keys);
var entry = bindingContext.ValidationState[bindingContext.Result.Model];
var strategy = Assert.IsType<ShortFormDictionaryValidationStrategy<int, ModelWithProperties>>(entry.Strategy);
Assert.Equal(
new KeyValuePair<string, int>[]
{
new KeyValuePair<string, int>("23", 23),
new KeyValuePair<string, int>("27", 27),
}.OrderBy(kvp => kvp.Key),
strategy.KeyMappings.OrderBy(kvp => kvp.Key));
}
示例9: ProcessAsync_WithItems_GeneratesExpectedOutput_DoesNotChangeSelectList
public async Task ProcessAsync_WithItems_GeneratesExpectedOutput_DoesNotChangeSelectList(
object model,
Type containerType,
Func<object> modelAccessor,
NameAndId nameAndId,
string expectedOptions)
{
// Arrange
var originalAttributes = new TagHelperAttributeList
{
{ "class", "form-control" },
};
var originalPostContent = "original content";
var expectedAttributes = new TagHelperAttributeList(originalAttributes)
{
{ "id", nameAndId.Id },
{ "name", nameAndId.Name },
{ "valid", "from validation attributes" },
};
var expectedPreContent = "original pre-content";
var expectedContent = "original content";
var expectedPostContent = originalPostContent + expectedOptions;
var expectedTagName = "select";
var metadataProvider = new TestModelMetadataProvider();
var containerMetadata = metadataProvider.GetMetadataForType(containerType);
var containerExplorer = metadataProvider.GetModelExplorerForType(containerType, model);
var propertyMetadata = metadataProvider.GetMetadataForProperty(containerType, "Text");
var modelExplorer = containerExplorer.GetExplorerForExpression(propertyMetadata, modelAccessor());
var modelExpression = new ModelExpression(nameAndId.Name, modelExplorer);
var tagHelperContext = new TagHelperContext(
allAttributes: new ReadOnlyTagHelperAttributeList<IReadOnlyTagHelperAttribute>(
Enumerable.Empty<IReadOnlyTagHelperAttribute>()),
items: new Dictionary<object, object>(),
uniqueId: "test");
var output = new TagHelperOutput(
expectedTagName,
originalAttributes,
getChildContentAsync: useCachedResult =>
{
var tagHelperContent = new DefaultTagHelperContent();
tagHelperContent.AppendHtml("Something");
return Task.FromResult<TagHelperContent>(tagHelperContent);
})
{
TagMode = TagMode.SelfClosing,
};
output.PreContent.AppendHtml(expectedPreContent);
output.Content.AppendHtml(expectedContent);
output.PostContent.AppendHtml(originalPostContent);
var htmlGenerator = new TestableHtmlGenerator(metadataProvider)
{
ValidationAttributes =
{
{ "valid", "from validation attributes" },
}
};
var viewContext = TestableHtmlGenerator.GetViewContext(model, htmlGenerator, metadataProvider);
var items = new SelectList(new[] { "", "outer text", "inner text", "other text" });
var savedDisabled = items.Select(item => item.Disabled).ToList();
var savedGroup = items.Select(item => item.Group).ToList();
var savedSelected = items.Select(item => item.Selected).ToList();
var savedText = items.Select(item => item.Text).ToList();
var savedValue = items.Select(item => item.Value).ToList();
var tagHelper = new SelectTagHelper(htmlGenerator)
{
For = modelExpression,
Items = items,
ViewContext = viewContext,
};
// Act
tagHelper.Init(tagHelperContext);
await tagHelper.ProcessAsync(tagHelperContext, output);
// Assert
Assert.Equal(TagMode.SelfClosing, output.TagMode);
Assert.Equal(expectedAttributes, output.Attributes);
Assert.Equal(expectedPreContent, output.PreContent.GetContent());
Assert.Equal(expectedContent, output.Content.GetContent());
Assert.Equal(expectedPostContent, HtmlContentUtilities.HtmlContentToString(output.PostContent));
Assert.Equal(expectedTagName, output.TagName);
Assert.Single(
tagHelperContext.Items,
entry => (Type)entry.Key == typeof(SelectTagHelper));
Assert.Equal(savedDisabled, items.Select(item => item.Disabled));
Assert.Equal(savedGroup, items.Select(item => item.Group));
Assert.Equal(savedSelected, items.Select(item => item.Selected));
Assert.Equal(savedText, items.Select(item => item.Text));
Assert.Equal(savedValue, items.Select(item => item.Value));
//.........这里部分代码省略.........
示例10: EnterNestedScope_FiltersValueProviders_BasedOnTopLevelValueProviders
public void EnterNestedScope_FiltersValueProviders_BasedOnTopLevelValueProviders()
{
// Arrange
var metadataProvider = new TestModelMetadataProvider();
metadataProvider
.ForProperty(typeof(string), nameof(string.Length))
.BindingDetails(b => b.BindingSource = BindingSource.Form);
var original = CreateDefaultValueProvider();
var context = DefaultModelBindingContext.CreateBindingContext(
new ActionContext(),
original,
metadataProvider.GetMetadataForType(typeof(string)),
new BindingInfo() { BindingSource = BindingSource.Query },
"model");
var propertyMetadata = metadataProvider.GetMetadataForProperty(typeof(string), nameof(string.Length));
// Act
context.EnterNestedScope(propertyMetadata, "Length", "Length", model: null);
// Assert
Assert.Collection(
Assert.IsType<CompositeValueProvider>(context.ValueProvider),
vp => Assert.Same(original[2], vp));
}
示例11: ProcessAsync_GeneratesExpectedOutput
public async Task ProcessAsync_GeneratesExpectedOutput(
object model,
Type containerType,
Func<object> modelAccessor,
NameAndId nameAndId,
string ignored)
{
// Arrange
var originalAttributes = new Dictionary<string, object>
{
{ "class", "form-control" },
};
var originalPostContent = "original content";
var expectedAttributes = new Dictionary<string, object>(originalAttributes)
{
{ "id", nameAndId.Id },
{ "name", nameAndId.Name },
{ "valid", "from validation attributes" },
};
var expectedPreContent = "original pre-content";
var expectedContent = "original content";
var expectedPostContent = originalPostContent;
var expectedTagName = "not-select";
var metadataProvider = new TestModelMetadataProvider();
var containerMetadata = metadataProvider.GetMetadataForType(containerType);
var containerExplorer = metadataProvider.GetModelExplorerForType(containerType, model);
var propertyMetadata = metadataProvider.GetMetadataForProperty(containerType, "Text");
var modelExplorer = containerExplorer.GetExplorerForExpression(propertyMetadata, modelAccessor());
var modelExpression = new ModelExpression(nameAndId.Name, modelExplorer);
var tagHelperContext = new TagHelperContext(
allAttributes: new Dictionary<string, object>(),
items: new Dictionary<object, object>(),
uniqueId: "test",
getChildContentAsync: () =>
{
var tagHelperContent = new DefaultTagHelperContent();
tagHelperContent.SetContent("Something");
return Task.FromResult<TagHelperContent>(tagHelperContent);
});
var output = new TagHelperOutput(expectedTagName, originalAttributes)
{
SelfClosing = true,
};
output.PreContent.SetContent(expectedPreContent);
output.Content.SetContent(expectedContent);
output.PostContent.SetContent(originalPostContent);
var htmlGenerator = new TestableHtmlGenerator(metadataProvider)
{
ValidationAttributes =
{
{ "valid", "from validation attributes" },
}
};
var viewContext = TestableHtmlGenerator.GetViewContext(model, htmlGenerator, metadataProvider);
var tagHelper = new SelectTagHelper
{
For = modelExpression,
Generator = htmlGenerator,
ViewContext = viewContext,
};
// Act
await tagHelper.ProcessAsync(tagHelperContext, output);
// Assert
Assert.True(output.SelfClosing);
Assert.Equal(expectedAttributes, output.Attributes);
Assert.Equal(expectedPreContent, output.PreContent.GetContent());
Assert.Equal(expectedContent, output.Content.GetContent());
Assert.Equal(expectedPostContent, output.PostContent.GetContent());
Assert.Equal(expectedTagName, output.TagName);
Assert.NotNull(viewContext.FormContext?.FormData);
Assert.Single(
viewContext.FormContext.FormData,
entry => entry.Key == SelectTagHelper.SelectedValuesFormDataKey);
}
示例12: CreateBinder_CreatesNoOpBinder_WhenPropertyBindingIsNotAllowed
public void CreateBinder_CreatesNoOpBinder_WhenPropertyBindingIsNotAllowed()
{
// Arrange
var metadataProvider = new TestModelMetadataProvider();
metadataProvider
.ForProperty<Widget>(nameof(Widget.Id))
.BindingDetails(m => m.IsBindingAllowed = false);
var modelBinder = new ByteArrayModelBinder();
var options = new TestOptionsManager<MvcOptions>();
options.Value.ModelBinderProviders.Add(new TestModelBinderProvider(c =>
{
if (c.Metadata.ModelType == typeof(WidgetId))
{
return modelBinder;
}
return null;
}));
var factory = new ModelBinderFactory(metadataProvider, options);
var context = new ModelBinderFactoryContext()
{
Metadata = metadataProvider.GetMetadataForProperty(typeof(Widget), nameof(Widget.Id)),
};
// Act
var result = factory.CreateBinder(context);
// Assert
Assert.NotNull(result);
Assert.IsType<NoOpBinder>(result);
}
示例13: BindModelAsync_ModelMetadataNotReadOnly_ModelNonNull_FailsSilently
public async Task BindModelAsync_ModelMetadataNotReadOnly_ModelNonNull_FailsSilently(int[] model)
{
// Arrange
var arrayLength = model.Length;
var valueProvider = new SimpleValueProvider
{
{ "someName[0]", "42" },
{ "someName[1]", "84" },
};
var bindingContext = GetBindingContext(valueProvider);
bindingContext.Model = model;
var metadataProvider = new TestModelMetadataProvider();
metadataProvider.ForProperty(
typeof(ModelWithIntArrayProperty),
nameof(ModelWithIntArrayProperty.ArrayProperty)).BindingDetails(bd => bd.IsReadOnly = false);
bindingContext.ModelMetadata = metadataProvider.GetMetadataForProperty(
typeof(ModelWithIntArrayProperty),
nameof(ModelWithIntArrayProperty.ArrayProperty));
var binder = new ArrayModelBinder<int>(new SimpleTypeModelBinder(typeof(int)));
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.True(bindingContext.Result.IsModelSet);
Assert.Same(model, bindingContext.Result.Model);
for (var i = 0; i < arrayLength; i++)
{
// Array should be unchanged.
Assert.Equal(357, model[i]);
}
}
示例14: GetModelBindingContext
private static DefaultModelBindingContext GetModelBindingContext(
IValueProvider valueProvider,
bool isReadOnly = false)
{
var metadataProvider = new TestModelMetadataProvider();
metadataProvider
.ForProperty<ModelWithIListProperty>(nameof(ModelWithIListProperty.ListProperty))
.BindingDetails(bd => bd.IsReadOnly = isReadOnly);
var metadata = metadataProvider.GetMetadataForProperty(
typeof(ModelWithIListProperty),
nameof(ModelWithIListProperty.ListProperty));
var bindingContext = new DefaultModelBindingContext
{
ModelMetadata = metadata,
ModelName = "someName",
ModelState = new ModelStateDictionary(),
ValueProvider = valueProvider,
ValidationState = new ValidationStateDictionary(),
FieldName = "testfieldname",
};
return bindingContext;
}
示例15: AddModelError_ForSingleExpression_AddsExpectedException
public void AddModelError_ForSingleExpression_AddsExpectedException()
{
// Arrange
var dictionary = new ModelStateDictionary();
var exception = new Exception();
var provider = new TestModelMetadataProvider();
var metadata = provider.GetMetadataForProperty(typeof(TestModel), nameof(TestModel.Text));
// Act
dictionary.AddModelError<TestModel>(model => model.Text, exception, metadata);
// Assert
var modelState = Assert.Single(dictionary);
var modelError = Assert.Single(modelState.Value.Errors);
Assert.Equal("Text", modelState.Key);
Assert.Same(exception, modelError.Exception);
}