我正試圖遷移到ASP.Net MVC 2並滿足一些問題。 這裏是一個: 我需要直接綁定詞典作爲查看帖子的結果。MVC 2,IModelBinder&ValueProvider更改
在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不是字典<>了,這是一個IValueProvider,只允許得到的值,它們的名字被稱爲
public interface IValueProvider
{
bool ContainsPrefix(string prefix);
ValueProviderResult GetValue(string key);
}
這實在是不冷靜,因爲我不能執行我的智能解析...
問:
- 是否有另一種方式來獲得所有的鑰匙?
- 你知道另一種方式來HTML元素的集合綁定到詞典
感謝您的建議
O.
在這裏看到:http://stackoverflow.com/questions/2290473/ivalueprovider-in-mvc-2-rc-2/2290520#2290520 – tvanfosson 2010-02-24 12:59:42