本文整理汇总了C#中ModelStateDictionary.ContainsKey方法的典型用法代码示例。如果您正苦于以下问题:C# ModelStateDictionary.ContainsKey方法的具体用法?C# ModelStateDictionary.ContainsKey怎么用?C# ModelStateDictionary.ContainsKey使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ModelStateDictionary
的用法示例。
在下文中一共展示了ModelStateDictionary.ContainsKey方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: AddExcepition
public static void AddExcepition(ModelStateDictionary ModelState, Exception ex)
{
if (ex is ArgumentException)
{
var argEx = (ArgumentException) ex;
if (!ModelState.ContainsKey(argEx.ParamName)) ModelState.Add(argEx.ParamName, new ModelState());
var lines = Regex.Split(ex.Message, "\r\n");
ModelState[argEx.ParamName].Errors.Add(new ModelError(ex, lines[0]));
return;
}
if (!ModelState.ContainsKey("")) ModelState.Add("", new ModelState());
ModelState[""].Errors.Add(new ModelError(ex, ex.Message));
}
示例2: CopyTempDataToModelState
private void CopyTempDataToModelState(ModelStateDictionary modelState,
TempDataDictionary tempData)
{
if (!tempData.ContainsKey(TempDataKey))
{
return;
}
ModelStateDictionary fromTempData = tempData[TempDataKey]
as ModelStateDictionary;
if (fromTempData == null)
{
return;
}
foreach (KeyValuePair<string, ModelState> pair in fromTempData)
{
if (modelState.ContainsKey(pair.Key))
{
modelState[pair.Key].Value = pair.Value.Value;
foreach (ModelError error in pair.Value.Errors)
{
modelState[pair.Key].Errors.Add(error);
}
}
else
{
modelState.Add(pair.Key, pair.Value);
}
}
}
示例3: CopyTempDataToModelState
private void CopyTempDataToModelState(ModelStateDictionary modelState, TempDataDictionary tempData)
{
if (!tempData.ContainsKey(TempDataKey)) return;
var fromTempData = tempData[TempDataKey] as ModelStateDictionary;
if (fromTempData == null) return;
foreach (var pair in fromTempData)
{
if (modelState.ContainsKey(pair.Key))
{
modelState[pair.Key].Value = pair.Value.Value;
foreach (var error in pair.Value.Errors)
{
if (!modelState[pair.Key].Errors.Contains(error))
modelState[pair.Key].Errors.Add(error);
}
}
else
{
modelState.Add(pair.Key, pair.Value);
}
}
}
示例4: GetProgressPercentage
/// <summary>
/// Used to calculate Model filling status in percentage
/// </summary>
/// <param name="modelState">Model state that contains information about filled fields</param>
/// <param name="prefix">Prefix that used to get full path to elemet returned from page</param>
public int GetProgressPercentage(ModelStateDictionary modelState, string prefix)
{
var successCnt = 0;
var errorCnt = 0;
var formattedList = this.GetAllPropertyFormattedList(this).Select(s => prefix + s).ToList();
foreach (var element in formattedList)
{
if (modelState.ContainsKey(element))
{
if (modelState[element].Errors.Count == 0)
{
if (!string.IsNullOrEmpty(modelState[element].Value.AttemptedValue))
{
successCnt++;
}
}
else
{
errorCnt++;
}
}
}
var totalCnt = successCnt + errorCnt;
return totalCnt == 0 ? 100 : (successCnt * 100 / totalCnt);
}
示例5: HasErrors
public static void HasErrors(ModelStateDictionary dict, string key, params ModelError[] errors)
{
Assert.True(dict.ContainsKey(key));
var state = dict[key];
Assert.Equal(
// Tuples have an Equals override. ModelError doesn't :(
errors.Select(e => Tuple.Create(e.Exception, e.ErrorMessage)).ToArray(),
state.Errors.Select(e => Tuple.Create(e.Exception, e.ErrorMessage)).ToArray());
}
示例6: ShouldCopyAllErrorsWithPrefix
public void ShouldCopyAllErrorsWithPrefix()
{
// arrange
NameValueCollection nvc = new NameValueCollection();
nvc.Add("Email", "Invalid");
nvc.Add("Email", "Mising");
nvc.Add("Password", "Mising");
ValidationException ex = new ValidationException { Errors = nvc };
ModelStateDictionary modelState = new ModelStateDictionary();
// act
ex.ToModelErrors(modelState, "credentials");
// assert
Assert.IsFalse(modelState.ContainsKey("Email"));
Assert.IsFalse(modelState.ContainsKey("Password"));
Assert.AreEqual(2, modelState["credentials.Email"].Errors.Count);
Assert.AreEqual(1, modelState["credentials.Password"].Errors.Count);
}
示例7: LogErrorAddsErrorToModelState
public void LogErrorAddsErrorToModelState()
{
ModelStateDictionary modelState = new ModelStateDictionary();
string prefix = "prefix";
IFormatterLogger formatterLogger = new ModelStateFormatterLogger(modelState, prefix);
formatterLogger.LogError("property", "error");
Assert.True(modelState.ContainsKey("prefix.property"));
Assert.Equal(1, modelState["prefix.property"].Errors.Count);
Assert.Equal("error", modelState["prefix.property"].Errors[0].ErrorMessage);
}
示例8: ReadAsync_UsesTryAddModelValidationErrorsToModelState
public async Task ReadAsync_UsesTryAddModelValidationErrorsToModelState()
{
// Arrange
var content = "{name: 'Person Name', Age: 'not-an-age'}";
var logger = GetLogger();
var formatter =
new JsonInputFormatter(logger, _serializerSettings, ArrayPool<char>.Shared, _objectPoolProvider);
var contentBytes = Encoding.UTF8.GetBytes(content);
var modelState = new ModelStateDictionary();
var httpContext = GetHttpContext(contentBytes);
var provider = new EmptyModelMetadataProvider();
var metadata = provider.GetMetadataForType(typeof(User));
var context = new InputFormatterContext(
httpContext,
modelName: string.Empty,
modelState: modelState,
metadata: metadata,
readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader);
modelState.MaxAllowedErrors = 3;
modelState.AddModelError("key1", "error1");
modelState.AddModelError("key2", "error2");
// Act
var result = await formatter.ReadAsync(context);
// Assert
Assert.True(result.HasError);
Assert.False(modelState.ContainsKey("age"));
var error = Assert.Single(modelState[""].Errors);
Assert.IsType<TooManyModelErrorsException>(error.Exception);
}
示例9: MergeDoesNothingIfParameterIsNull
public void MergeDoesNothingIfParameterIsNull()
{
// Arrange
var dictionary = new ModelStateDictionary() { { "foo", new ModelStateEntry() } };
// Act
dictionary.Merge(null);
// Assert
Assert.Single(dictionary);
Assert.True(dictionary.ContainsKey("foo"));
}
示例10: ContainsKey_ReturnsTrue_IfNodeHasBeenMutated
public void ContainsKey_ReturnsTrue_IfNodeHasBeenMutated(string key)
{
// Arrange
var dictionary = new ModelStateDictionary();
dictionary.MarkFieldSkipped(key);
// Act
var result = dictionary.ContainsKey(key);
// Assert
Assert.True(result);
}
示例11: IsPasswordValidFalse
public void IsPasswordValidFalse()
{
var service = GetMockedUserService();
var modelState = new ModelStateDictionary();
var result = service.IsPasswordValid("12345", modelState);
Assert.False(result);
Assert.AreEqual(1, modelState.Count);
Assert.True(modelState.ContainsKey("Password"));
}
示例12: SetLogo
private void SetLogo(EditEventViewModel viewModel, ModelStateDictionary modelState)
{
bool hasLogo = Session[CurrentLogoKey] != null;
if(hasLogo)
{
viewModel.Logo = (byte[])Session[CurrentLogoKey];
viewModel.IsLogoSetted = true;
viewModel.HasLogo = true;
if(modelState.ContainsKey("HasLogo"))
modelState.Remove("HasLogo");
}
}
示例13: Should_add_to_modelstate_without_prefix
public void Should_add_to_modelstate_without_prefix()
{
var thing = new Thing();
var form = new FormCollection
{
{ "Age", "not a number" }
};
var modelState = new ModelStateDictionary();
try
{
validatingBinder.UpdateFrom(thing, form, modelState);
}
catch {}
finally
{
modelState.ContainsKey("Age").ShouldBeTrue();
}
}
示例14: CreateUser_would_report_error_if_the_creator_has_no_rights
public void CreateUser_would_report_error_if_the_creator_has_no_rights()
{
SetUpEmptyUserExpectationForCreateNewAccountWithValidConditions();
var modelError = new ModelStateDictionary();
_userAuthenticationServiceSUT.Create(null, _nonExistignUserName, modelError);
Assert.True(modelError.ContainsKey(string.Empty));
Assert.True(modelError.ContainsError(string.Empty, AccountString.CreatorLackOfRight));
}
示例15: NullCheckFailedHandler_ModelStateAlreadyInvalid_DoesNothing
public void NullCheckFailedHandler_ModelStateAlreadyInvalid_DoesNothing()
{
// Arrange
var modelState = new ModelStateDictionary();
modelState.AddModelError("foo.bar", "Some existing error.");
var modelMetadata = GetMetadataForType(typeof(Person));
var validationNode = new ModelValidationNode(modelMetadata, "foo");
var validationContext = new ModelValidationContext(new DataAnnotationsModelMetadataProvider(),
Enumerable.Empty<IModelValidatorProvider>(),
modelState,
modelMetadata,
null);
var e = new ModelValidatedEventArgs(validationContext, parentNode: null);
// Act
var handler = MutableObjectModelBinder.CreateNullCheckFailedHandler(modelMetadata, incomingValue: null);
handler(validationNode, e);
// Assert
Assert.False(modelState.ContainsKey("foo"));
}