ASP.Net MVC 2 に移行していくつかの問題を解決しようとしています。ここに 1 つあります。ビュー ポストの結果として、 Dictionaryを直接バインドする必要がありました。
ASP.Net MVC 1 では、カスタムIModelBinderを使用して完全に機能しました。
/// <summary>
/// Bind Dictionary<int, int>
///
/// convention : <elm name="modelName_key" value="value"></elm>
/// </summary>
public class DictionaryModelBinder : IModelBinder
{
#region IModelBinder Members
/// <summary>
/// Mandatory
/// </summary>
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
IDictionary<int, int> retour = new Dictionary<int, int>();
// get the values
var values = bindingContext.ValueProvider;
// get the model name
string modelname = bindingContext.ModelName + '_';
int skip = modelname.Length;
// loop on the keys
foreach(string keyStr in values.Keys)
{
// if an element has been identified
if(keyStr.StartsWith(modelname))
{
// get that key
int key;
if(Int32.TryParse(keyStr.Substring(skip), out key))
{
int value;
if(Int32.TryParse(values[keyStr].AttemptedValue, out value))
retour.Add(key, value);
}
}
}
return retour;
}
#endregion
}
データの辞書を表示するいくつかのスマートな HtmlBuilder とペアで動作しました。
私が今直面している問題は、ValueProviderが Dictionary<> ではなく、名前がわかっている値のみを取得できる IValueProvider であることです。
public interface IValueProvider
{
bool ContainsPrefix(string prefix);
ValueProviderResult GetValue(string key);
}
スマートな解析を実行できないため、これは本当にクールではありません...
質問 :
- すべてのキーを取得する別の方法はありますか?
- HTML 要素のコレクションを Dictionary にバインドする別の方法を知っていますか?
ご提案いただきありがとうございます
O.