【发布时间】:2015-09-15 10:15:25
【问题描述】:
我正在尝试迁移到 ASP.Net MVC 2 并遇到一些问题。 这是一个: 我需要直接绑定 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 元素集合绑定到字典的方法
感谢您的建议
哦。
【问题讨论】:
标签: asp.net-mvc-2 imodelbinder