我有以下两种模型:
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
,而我不这样做。不想暴露我的一些财产。
老实说,在我看来,这种情况下的定制模型装订员实在是太过分了。
如果您不想公开internal MyOtherClass
的某些属性,为什么不创建一个Dto模型,例如MyOtherClassDto
,它仅公开那些必须通过API访问的属性