// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Globalization;
using System.Threading.Tasks;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Mvc.ModelBinding
{
///
/// An adapter for data stored in an
/// .
///
public class DictionaryBasedValueProvider: BindingSourceValueProvider
{
private readonly IDictionary _values;
private PrefixContainer _prefixContainer;
///
/// Creates a new .
///
/// The of the data.
/// The values.
public DictionaryBasedValueProvider(
[NotNull] BindingSource bindingSource,
[NotNull] IDictionary values)
: base(bindingSource)
{
_values = values;
}
protected PrefixContainer PrefixContainer
{
get
{
if (_prefixContainer == null)
{
_prefixContainer = new PrefixContainer(_values.Keys);
}
return _prefixContainer;
}
}
///
public override Task ContainsPrefixAsync(string key)
{
return Task.FromResult(PrefixContainer.ContainsPrefix(key));
}
///
public override Task GetValueAsync([NotNull] string key)
{
object value;
ValueProviderResult result;
if (_values.TryGetValue(key, out value))
{
var stringValue = value as string ?? value?.ToString() ?? string.Empty;
result = new ValueProviderResult(stringValue, CultureInfo.InvariantCulture);
}
else
{
result = ValueProviderResult.None;
}
return Task.FromResult(result);
}
}
}