gpt4 book ai didi

asp.net - 迭代 ModelBindingContext.ValueProvider

转载 作者:行者123 更新时间:2023-12-05 05:17:23 27 4
gpt4 key购买 nike

我有不止一个属性需要获取,它们以相同的前缀开头,但我只能通过键获得 ModelBindingContext.ValueProvider 的确切值。 .有没有办法获取多个 ValueProvider 或迭代 System.Web.Mvc.DictionaryValueProvider<object>

 var value = bindingContext.ValueProvider.GetValue(propertyDescriptor.Name);

这样做的原因是一个名为 Settings 的动态属性,它将绑定(bind)到下面的 json 属性。现在设置上没有名为“启用”的属性,因此它不能正常绑定(bind)。

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);
}
}

关于asp.net - 迭代 ModelBindingContext.ValueProvider,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49309931/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com