MVC 4 列表模型绑定如何工作? [英] How does MVC 4 List Model Binding work?

查看:29
本文介绍了MVC 4 列表模型绑定如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想将表单中的一组输入绑定到 MVC 4 中的 List,我知道 input name<的以下命名约定/code> 属性将起作用:

If I want a set of inputs in a form to bind to a List in MVC 4, I know that the following naming convention for input name attributes will work:

<input name="[0].Id" type="text" />
<input name="[1].Id" type="text" />
<input name="[2].Id" type="text" />

但我很好奇模型活页夹的宽容度.例如,以下情况如何:

But I am curious about how forgiving the model binder is. For example, what about the following:

<input name="[0].Id" type="text" />
<input name="[3].Id" type="text" />
<input name="[8].Id" type="text" />

模型绑定器将如何处理这个问题?它会绑定到一个长度为 9 的带有空值的 List 吗?或者它仍然会绑定到长度为 3 的 List 吗?还是会完全窒息?

How would the model binder handle this? Would it bind to a List of length 9 with nulls? Or would it still bind to a List of length 3? Or would it choke altogether?

我为什么关心

我想实现一个动态表单,用户可以在其中向表单添加行,也可以从表单中删除行.因此,如果我的用户删除了 8 行中的第 2 行,我想知道是否需要对所有后续输入重新编号.

I want to implement a dynamic form in which the user may add rows to the form, and also may delete rows from the form. So if I a user deletes row 2 out of 8 total rows, I want to know if I'll need to renumber all of the subsequent inputs.

推荐答案

有一种用于集合的特定连线格式.这在 Scott Hanselman 的博客上有讨论:

There is a specific wire format for use with collections. This is discussed on Scott Hanselman's blog here:

http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx

Phil Haack 的另一篇博客文章在这里谈到了这一点:

Another blog entry from Phil Haack talks about this here:

http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

最后,一个完全符合您要求的博客条目:

Finally, a blog entry that does exactly what you want here:

http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/

这篇关于MVC 4 列表模型绑定如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆