c# - 在 ASP.NET MVC 的自定义模型 Binder 中绑定(bind)属于另一个对象的列表

标签 c# asp.net-mvc model

我知道有人问过这样的问题,但这可能有点不同。

下面是我的事件对象:

Event : IEvent
  public int Id
  public string Title
  public List<EventContact> Contacts

和 EventContact:

EventContact
  public int Id
  public string Name
  public string Email

因此,Event 有一个 EventContact 对象列表。现在,Event 还实现了 IEvent - 因此是自定义模型绑定(bind)器。我使用 IEvent 而不是 Event,因此当默认模型联编程序尝试执行它的操作时,它让我知道它无法创建“IEvent”。

我的 View 中填充了联系信息:

<input type="text" name="contact[0].Name" value="DB Value"/>
<input type="text" name="contact[1].Name" value="DB Value"/>
<input type="text" name="contact[2].Name" value="DB Value"/>

<input type="text" name="contact[0].Email" value="DB Value"/>
<input type="text" name="contact[1].Email" value="DB Value"/>
<input type="text" name="contact[2].Email" value="DB Value"/>

<!-- Event fields, etc -->

因此,在我的自定义模型 Binder 中,我能够看到所有值 - 太棒了!唯一的问题是,我真的不确定如何获取所有联系人字段并从中创建联系人列表,以及绑定(bind)所有事件字段。

最佳答案

为了实现上述目标,我只是查询了现有绑定(bind)上下文的 ValueProvider 以获取所有 EventContact 字段,并将其与新的绑定(bind)上下文一起发送到默认模型绑定(bind)器:

IDictionary<string, ValueProviderResult> contactValueProvider = bindingContext.ValueProvider
            .Select(t => new { t.Key, t.Value })
            .Where(t => t.Key.Contains("EventContact"))
            .ToDictionary(t => t.Key, t => t.Value);

ModelBindingContext contactBindingContext = new ModelBindingContext()
        {
            ModelName = "EventContact",
            ModelState = bindingContext.ModelState,
            ModelType = typeof(List<EventContact>),
            PropertyFilter = bindingContext.PropertyFilter,
            ValueProvider = contactValueProvider
        };

_event.Contacts = ModelBinders.Binders.DefaultBinder.BindModel(controllerContext, contactBindingContext) as IQueryable<EventContact>;

它有效,所以我很高兴 :P

关于c# - 在 ASP.NET MVC 的自定义模型 Binder 中绑定(bind)属于另一个对象的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2429905/

相关文章:

c# - Enumerable.Intersperse 的扩展方法?

asp.net-mvc - return Json 将在指定 Url 时重定向到另一个 View

asp.net - 如何强制 Web API 识别查询字符串参数

android - 在 Android Studio 中创建一个 android 模型类

c# - MVC : Run a method on Application startup without calling it from Application_Start

C# 为 WebClient 使用代理

jquery - ASP.net MVC 验证在不正确的字段上突出显示和图标 Jquery

django - 使用注册表单添加到自定义用户字段(django)

Java 模式问题 - 模型中的构建器或数据库代码?

c# - 为什么向结构体添加一个额外的字段会大大提高其性能?