【问题标题】:Model Binding with Internal List与内部列表的模型绑定
【发布时间】: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


    【解决方案1】:

    老实说,在我看来,这种情况下的自定义模型绑定器有点矫枉过正。

    如果您不想公开internal MyOtherClass 中的某些属性,为什么不直接创建一个 Dto 模型,例如 MyOtherClassDto,它只会公开必须通过 API 访问的那些属性

    【讨论】:

    • 感谢您的回答,但我不确定这将如何工作,因为我需要通过模型绑定器在 API 之外设置内部属性
    猜你喜欢
    • 1970-01-01
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多