本文整理汇总了C#中TestModelMetadataProvider.ForProperty方法的典型用法代码示例。如果您正苦于以下问题:C# TestModelMetadataProvider.ForProperty方法的具体用法?C# TestModelMetadataProvider.ForProperty怎么用?C# TestModelMetadataProvider.ForProperty使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类TestModelMetadataProvider
的用法示例。
在下文中一共展示了TestModelMetadataProvider.ForProperty方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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); });
}
示例2: 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);
}
示例3: DisplayNameHelpers_ReturnDisplayNameForProperty_IfNonNull
public void DisplayNameHelpers_ReturnDisplayNameForProperty_IfNonNull(string displayName)
{
// Arrange
var provider = new TestModelMetadataProvider();
provider
.ForProperty<DefaultTemplatesUtilities.ObjectTemplateModel>("Property1")
.DisplayDetails(dd => dd.DisplayName = () => displayName);
var helper = DefaultTemplatesUtilities.GetHtmlHelper(provider: provider);
var enumerableHelper = DefaultTemplatesUtilities.GetHtmlHelperForEnumerable(provider: provider);
// Act
var displayNameResult = helper.DisplayName("Property1");
var displayNameForResult = helper.DisplayNameFor(m => m.Property1);
var displayNameForEnumerableResult = enumerableHelper.DisplayNameFor(m => m.Property1);
// Assert
Assert.Equal(displayName, displayNameResult);
Assert.Equal(displayName, displayNameForResult);
Assert.Equal(displayName, displayNameForEnumerableResult);
}
示例4: ProcessAsync_CallsGenerateTextBox_AddsExpectedAttributes
public async Task ProcessAsync_CallsGenerateTextBox_AddsExpectedAttributes(
string dataTypeName,
string expectedFormat,
string expectedType)
{
// Arrange
var expectedAttributes = new TagHelperAttributeList
{
{ "type", expectedType }, // Calculated; not passed to HtmlGenerator.
};
var expectedTagName = "not-input";
var context = new TagHelperContext(
allAttributes: new ReadOnlyTagHelperAttributeList<IReadOnlyTagHelperAttribute>(
Enumerable.Empty<IReadOnlyTagHelperAttribute>()),
items: new Dictionary<object, object>(),
uniqueId: "test",
getChildContentAsync: useCachedResult => Task.FromResult<TagHelperContent>(new DefaultTagHelperContent()));
var output = new TagHelperOutput(expectedTagName, attributes: new TagHelperAttributeList())
{
TagMode = TagMode.SelfClosing,
};
var metadataProvider = new TestModelMetadataProvider();
metadataProvider.ForProperty<Model>("Text").DisplayDetails(dd => dd.DataTypeName = dataTypeName);
var htmlGenerator = new Mock<IHtmlGenerator>(MockBehavior.Strict);
var tagHelper = GetTagHelper(
htmlGenerator.Object,
model: null,
propertyName: nameof(Model.Text),
metadataProvider: metadataProvider);
var tagBuilder = new TagBuilder("input");
var htmlAttributes = new Dictionary<string, object>
{
{ "type", expectedType }
};
if (string.Equals(dataTypeName, TemplateRenderer.IEnumerableOfIFormFileName))
{
htmlAttributes["multiple"] = "multiple";
}
htmlGenerator
.Setup(mock => mock.GenerateTextBox(
tagHelper.ViewContext,
tagHelper.For.ModelExplorer,
tagHelper.For.Name,
null, // value
expectedFormat,
htmlAttributes)) // htmlAttributes
.Returns(tagBuilder)
.Verifiable();
// Act
await tagHelper.ProcessAsync(context, output);
// Assert
htmlGenerator.Verify();
Assert.Equal(TagMode.SelfClosing, output.TagMode);
Assert.Equal(expectedAttributes, output.Attributes);
Assert.Empty(output.PreContent.GetContent());
Assert.Equal(string.Empty, output.Content.GetContent());
Assert.Empty(output.PostContent.GetContent());
Assert.Equal(expectedTagName, output.TagName);
}
示例5: ProcessAsync_CallsGenerateTextBox_WithExpectedParameters
public async Task ProcessAsync_CallsGenerateTextBox_WithExpectedParameters(
string dataTypeName,
string inputTypeName,
string model)
{
// Arrange
var contextAttributes = new TagHelperAttributeList
{
{ "class", "form-control" },
};
if (!string.IsNullOrEmpty(inputTypeName))
{
contextAttributes["type"] = inputTypeName; // Support restoration of type attribute, if any.
}
var expectedAttributes = new TagHelperAttributeList
{
{ "class", "form-control text-control" },
{ "type", inputTypeName ?? "text" }, // Generator restores type attribute; adds "text" if none.
};
var expectedPreContent = "original pre-content";
var expectedContent = "original content";
var expectedPostContent = "original post-content";
var expectedTagName = "not-input";
var context = new TagHelperContext(
allAttributes: contextAttributes,
items: new Dictionary<object, object>(),
uniqueId: "test",
getChildContentAsync: useCachedResult =>
{
var tagHelperContent = new DefaultTagHelperContent();
tagHelperContent.SetContent("Something");
return Task.FromResult<TagHelperContent>(tagHelperContent);
});
var originalAttributes = new TagHelperAttributeList
{
{ "class", "form-control" },
};
var output = new TagHelperOutput(expectedTagName, originalAttributes)
{
TagMode = TagMode.StartTagOnly,
};
output.PreContent.SetContent(expectedPreContent);
output.Content.SetContent(expectedContent);
output.PostContent.SetContent(expectedPostContent);
var metadataProvider = new TestModelMetadataProvider();
metadataProvider.ForProperty<Model>("Text").DisplayDetails(dd => dd.DataTypeName = dataTypeName);
var htmlGenerator = new Mock<IHtmlGenerator>(MockBehavior.Strict);
var tagHelper = GetTagHelper(
htmlGenerator.Object,
model,
nameof(Model.Text),
metadataProvider: metadataProvider);
tagHelper.InputTypeName = inputTypeName;
var tagBuilder = new TagBuilder("input")
{
Attributes =
{
{ "class", "text-control" },
},
};
htmlGenerator
.Setup(mock => mock.GenerateTextBox(
tagHelper.ViewContext,
tagHelper.For.ModelExplorer,
tagHelper.For.Name,
model, // value
null, // format
It.Is<Dictionary<string, object>>(m => m.ContainsKey("type")))) // htmlAttributes
.Returns(tagBuilder)
.Verifiable();
// Act
await tagHelper.ProcessAsync(context, output);
// Assert
htmlGenerator.Verify();
Assert.Equal(TagMode.StartTagOnly, output.TagMode);
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);
}
示例6: LabelHelpers_DisplayDisplayNameForProperty_IfNonNull
public void LabelHelpers_DisplayDisplayNameForProperty_IfNonNull(string displayName)
{
// Arrange
var provider = new TestModelMetadataProvider();
provider
.ForProperty<DefaultTemplatesUtilities.ObjectTemplateModel>("Property1")
.DisplayDetails(dd => dd.DisplayName = displayName);
var helper = DefaultTemplatesUtilities.GetHtmlHelper(provider: provider);
// Act
var labelResult = helper.Label("Property1");
var labelForResult = helper.LabelFor(m => m.Property1);
// Assert
Assert.Equal("<label for=\"HtmlEncode[[Property1]]\">HtmlEncode[[" + displayName + "]]</label>", labelResult.ToString());
Assert.Equal("<label for=\"HtmlEncode[[Property1]]\">HtmlEncode[[" + displayName + "]]</label>", labelForResult.ToString());
}
示例7: LabelHelpers_ReturnEmptyForProperty_IfDisplayNameEmpty
public void LabelHelpers_ReturnEmptyForProperty_IfDisplayNameEmpty()
{
// Arrange
var provider = new TestModelMetadataProvider();
provider
.ForProperty<DefaultTemplatesUtilities.ObjectTemplateModel>("Property1")
.DisplayDetails(dd => dd.DisplayName = string.Empty);
var modelExplorer = provider
.GetModelExplorerForType(typeof(DefaultTemplatesUtilities.ObjectTemplateModel), model: null)
.GetExplorerForProperty("Property1");
var helper = DefaultTemplatesUtilities.GetHtmlHelper();
// Act
var labelResult = helper.Label(expression: string.Empty);
var labelNullResult = helper.Label(expression: null); // null is another alias for current model
var labelForResult = helper.LabelFor(m => m);
var labelForModelResult = helper.LabelForModel();
// Assert
Assert.Empty(labelResult.ToString());
Assert.Empty(labelNullResult.ToString());
Assert.Empty(labelForResult.ToString());
Assert.Empty(labelForModelResult.ToString());
}
示例8: 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;
}
示例9: 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;
}
示例10: GetBindingContext
private static DefaultModelBindingContext GetBindingContext(
IValueProvider valueProvider,
bool isReadOnly = false)
{
var metadataProvider = new TestModelMetadataProvider();
metadataProvider.ForProperty(
typeof(ModelWithIntArrayProperty),
nameof(ModelWithIntArrayProperty.ArrayProperty)).BindingDetails(bd => bd.IsReadOnly = isReadOnly);
var modelMetadata = metadataProvider.GetMetadataForProperty(
typeof(ModelWithIntArrayProperty),
nameof(ModelWithIntArrayProperty.ArrayProperty));
var bindingContext = new DefaultModelBindingContext
{
ModelMetadata = modelMetadata,
ModelName = "someName",
ModelState = new ModelStateDictionary(),
ValueProvider = valueProvider,
OperationBindingContext = new OperationBindingContext
{
MetadataProvider = metadataProvider,
},
};
return bindingContext;
}
示例11: 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);
}
示例12: FromBodyOnPropertyType_WithData_Succeeds
public async Task FromBodyOnPropertyType_WithData_Succeeds(BindingInfo bindingInfo)
{
// Arrange
var inputText = "{ \"Street\" : \"someStreet\" }";
var metadataProvider = new TestModelMetadataProvider();
metadataProvider
.ForProperty<Person6>(nameof(Person6.Address))
.BindingDetails(binding => binding.BindingSource = BindingSource.Body);
var argumentBinder = ModelBindingTestHelper.GetArgumentBinder(metadataProvider);
var parameter = new ParameterDescriptor
{
Name = "parameter-name",
BindingInfo = bindingInfo,
ParameterType = typeof(Person6),
};
var testContext = ModelBindingTestHelper.GetTestContext(
request =>
{
request.Body = new MemoryStream(Encoding.UTF8.GetBytes(inputText));
request.ContentType = "application/json";
});
testContext.MetadataProvider = metadataProvider;
var modelState = testContext.ModelState;
// Act
var modelBindingResult = await argumentBinder.BindModelAsync(parameter, testContext);
// Assert
Assert.True(modelBindingResult.IsModelSet);
var person = Assert.IsType<Person6>(modelBindingResult.Model);
Assert.NotNull(person.Address);
Assert.Equal("someStreet", person.Address.Street, StringComparer.Ordinal);
Assert.True(modelState.IsValid);
Assert.Empty(modelState);
}
示例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: ObjectTemplate_HonoursHideSurroundingHtml
public void ObjectTemplate_HonoursHideSurroundingHtml()
{
// Arrange
var expected =
"Model = p1, ModelType = System.String, PropertyName = Property1, SimpleDisplayText = p1" +
"<div class=\"HtmlEncode[[display-label]]\">HtmlEncode[[Prop2]]</div>" + Environment.NewLine +
"<div class=\"HtmlEncode[[display-field]]\">Model = (null), ModelType = System.String, PropertyName = Property2," +
" SimpleDisplayText = (null)</div>" + Environment.NewLine;
var model = new DefaultTemplatesUtilities.ObjectTemplateModel { Property1 = "p1", Property2 = null };
var provider = new TestModelMetadataProvider();
provider.ForProperty<DefaultTemplatesUtilities.ObjectTemplateModel>("Property1").DisplayDetails(dd =>
{
dd.HideSurroundingHtml = true;
});
var html = DefaultTemplatesUtilities.GetHtmlHelper(model, provider);
// Act
var result = DefaultDisplayTemplates.ObjectTemplate(html);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
示例15: AddValidation_WithErrorMessageAndDisplayName_SetsAttributesAsExpected
public void AddValidation_WithErrorMessageAndDisplayName_SetsAttributesAsExpected()
{
// Arrange
var expected = "Error about 'Display Length' from override.";
var attribute = new RemoteAttribute("Action", "Controller")
{
HttpMethod = "POST",
ErrorMessage = "Error about '{0}' from override.",
};
var url = "/Controller/Action";
var metadataProvider = new TestModelMetadataProvider();
metadataProvider
.ForProperty(typeof(string), nameof(string.Length))
.DisplayDetails(d => d.DisplayName = () => "Display Length");
var context = GetValidationContext(url, metadataProvider);
// Act
attribute.AddValidation(context);
// Assert
Assert.Collection(
context.Attributes,
kvp => { Assert.Equal("data-val", kvp.Key); Assert.Equal("true", kvp.Value); },
kvp =>
{
Assert.Equal("data-val-remote", kvp.Key);
Assert.Equal(expected, kvp.Value);
},
kvp =>
{
Assert.Equal("data-val-remote-additionalfields", kvp.Key);
Assert.Equal("*.Length", kvp.Value);
},
kvp => { Assert.Equal("data-val-remote-type", kvp.Key); Assert.Equal("POST", kvp.Value); },
kvp => { Assert.Equal("data-val-remote-url", kvp.Key); Assert.Equal(url, kvp.Value); });
}