【发布时间】:2020-05-15 17:31:55
【问题描述】:
我有两个模型如下:
public class MyMainClass
{
internal List<MyOtherClass> {get; set;}
public int SomeValue {get; set;}
}
public class MyOtherClass
{
public int SomeOtherValue {get; set;}
}
我希望能够将MyMainClass 绑定为我的控制器中的参数,并填充内部属性。例如:
[HttpPost]
public ActionResult DoSomething(MyMainClass myMainClass)
从我的阅读来看,似乎为了绑定一个内部属性,我需要创建自己的模型绑定器,我已经在下面完成了:
public class MyOtherClassBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
MyOtherClass model = (MyOtherClass) (bindingContext.Model ?? new MyOtherClass());
model.SomeOtherValue = GetValue<int>(bindingContext, nameof(MyOtherClass.SomeOtherValue));
model.ColumnConfigurations = GetValue<List<WebTableColumnConfiguration>>(bindingContext, nameof(WebTableConfiguration.ColumnConfigurations));
return model;
}
private T GetValue<T>(ModelBindingContext bindingContext, string key)
{
ValueProviderResult result = bindingContext.ValueProvider.GetValue(key);
return (T)result.ConvertTo(typeof(T));
}
}
public class MyMainClassBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
MyMainClass model = (MyMainClass) (bindingContext.Model ?? new MyMainClass());
model.SomeValue = GetValue<int>(bindingContext, nameof(MyMainClass.SomeValue));
model.Items = GetValue<List<MyOtherClass>>(bindingContext, nameof(MyMainClass.Items));
return model;
}
private T GetValue<T>(ModelBindingContext bindingContext, string key)
{
ValueProviderResult result = bindingContext.ValueProvider.GetValue(key);
return (T)result.ConvertTo(typeof(T));
}
}
但是,当我尝试获取 Items 的值时,我的模型绑定程序失败,ValueProviderResult 为空,可能是因为它找不到该值。在调试器中,如果我检查ValueProvider 并向下钻取FormValueProvider,我可以看到Items 列表中有值:
{[items[0][SomeOtherValue], System.Web.Mvc.NameValueCollectionValueProvider+ValueProviderResultPlaceholder]}
{[items[1][SomeOtherValue], System.Web.Mvc.NameValueCollectionValueProvider+ValueProviderResultPlaceholder]}
如何让我的自定义模型绑定器正确绑定我的自定义项列表?这甚至是正确的方法吗?
我确定如果我创建了属性 public 而不是 internal 它可以在没有自定义模型绑定器的情况下工作,但是这些类将成为库的一部分,其中消费应用程序将从 MyMainClass 子类化而我不这样做'不想让我的一些属性暴露出来。
【问题讨论】:
标签: c# asp.net-mvc model-binding