MVC 2,Imodelbinder和ValueProvider的更改
-
22-09-2019 - |
题
我试图迁移到ASP.NET MVC 2并遇到一些问题。这是一个:我需要直接绑定 字典 作为视图帖子的结果。
在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.
解决方案
我认为您将不再在MVC 2中这样做。
另外,您可以扩展DefaultModelBinder并覆盖其虚拟方法之一,例如GetModelProperties,然后更改ModelBindingContext内部的modelname。另一个选项是为您的字典类型实现自定义的元数据,您也可以在此更改模型名称。
其他提示
尽管这个问题已被标记为“回答”,但我认为以下问题可能会有所帮助。我遇到了同样的问题,并查看了系统的源代码.web.mvc.defaultvalueprovider。它从routedata,查询字符串或请求表单提交(以该确切的顺序)获取其值。要收集所有键(这是您在第一个问题中要求的),我写了以下助手方法。
private static IEnumerable<string> GetKeys(ControllerContext context)
{
List<string> keys = new List<string>();
HttpRequestBase request = context.HttpContext.Request;
keys.AddRange(((IDictionary<string,
object>)context.RouteData.Values).Keys.Cast<string>());
keys.AddRange(request.QueryString.Keys.Cast<string>());
keys.AddRange(request.Form.Keys.Cast<string>());
return keys;
}
您可以使用此方法来枚举键:
foreach (string key in GetKeys(controllerContext))
{
// Do something with the key value.
}
不隶属于 StackOverflow