我有一个自定义模型活页夹,它将发布的值转换为另一个模型。问题是,即使从客户端发布了值,bindingContext.ValueProvider.GetValue(modelName)
也不会返回任何值。
动作方法
[HttpPost]
public ActionResult Update([DataSourceRequest] DataSourceRequest request,
[Bind(Prefix = "models")] AnotherModel items)
{
return Ok();
}
目标模型类别
[ModelBinder(BinderType = typeof(MyModelBinder))]
public class AnotherModel
{
IEnumerable<Dictionary<string, object>> Items { get; set; }
}
Cutomer Model Binder
public class MyModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
var modelName = bindingContext.ModelName;
// ISSUE: valueProviderResult is always None
var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);
if (valueProviderResult == ValueProviderResult.None)
{
return Task.CompletedTask;
}
//here i will convert valueProviderResult to AnotherModel
return Task.CompletedTask;
}
}
快速观察显示ValueProvider确实具有值
UPDATE1
当我可以通过IFormCollection进行迭代时,在Update操作方法中,Request.Form具有所有的键和值对。不确定为什么模型联编程序无法检索它。
foreach (var f in HttpContext.Request.Form)
{
var key = f.Key;
var v = f.Value;
}
如果检查MVC CollectionModelBinder的源代码,您会注意到“ name [index]”形式的值将返回ValueProviderResult。无,需要单独处理。
似乎您正在尝试解决错误的问题。我建议绑定到像Dictionary
这样的标准集合类。
任何一个]]
public ActionResult Update([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")] Dictionary<string, RecordTypeName> items)
或;
public class AnotherModel : Dictionary<string, RecordTypeName> {}
如果您不知道每个字典值在编译时将具有哪种类型,那就是自定义活页夹将派上用场的地方。