我有多个要抓取的属性,该属性以相同的前缀开头,但我只能通过ModelBindingContext.ValueProvider
的键来获取确切的值。有没有办法获取多个ValueProvider或迭代System.Web.Mvc.DictionaryValueProvider<object>
?
var value = bindingContext.ValueProvider.GetValue(propertyDescriptor.Name);
这样做的原因是一个名为Settings的动态属性,它将绑定到下面的json属性。目前,“设置”上没有名为“启用”的属性,因此它无法正常绑定。
public class Integration
{
public dynamic Settings {get;set;}
}
"Integrations[0].Settings.Enable": "true"
"Integrations[0].Settings.Name": "Will"
知道了
public class DynamicPropertyBinder : PropertyBinderAttribute
{
public override bool BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
{
if (propertyDescriptor.PropertyType == typeof(Object))
{
foreach(var valueProvider in bindingContext.ValueProvider as System.Collections.IList)
{
var dictionary = valueProvider as DictionaryValueProvider<object>;
if (dictionary != null)
{
var keys = dictionary.GetKeysFromPrefix($"{bindingContext.ModelName}.{propertyDescriptor.Name}");
if (keys.Any())
{
var expando = new ExpandoObject();
foreach (var key in keys)
{
var keyValue = dictionary.GetValue(key.Value);
if (keyValue != null)
{
AddProperty(expando, key.Key, keyValue.RawValue);
}
}
propertyDescriptor.SetValue(bindingContext.Model, expando);
return true;
}
}
}
}
return false;
}
public static void AddProperty(ExpandoObject expando, string propertyName, object propertyValue)
{
var expandoDict = expando as IDictionary<string, object>;
if (expandoDict.ContainsKey(propertyName))
expandoDict[propertyName] = propertyValue;
else
expandoDict.Add(propertyName, propertyValue);
}
}
这是一个古老的问题,但是我将发布找到的解决方案。
您可以从请求对象中获取所有提交的键,然后对其进行迭代以获取实际值:
var keys = controllerContext.RequestContext.HttpContext.Request.Form.AllKeys.ToList();
foreach (var key in keys)
{
var value = bindingContext.ValueProvider.GetValue(key).AttemptedValue;
}