【问题标题】:List property ignored by controller if 0 index is missing如果缺少 0 索引,控制器将忽略列表属性
【发布时间】:2017-10-08 10:56:41
【问题描述】:

我正在使用 mongodb 在 c# .net mvc 中构建一个网络表单来存储信息。该表单与一个公司对象一起使用,该对象的属性是一个地址列表,称为地址数据。提交表单时,公司对象被发送到控制器,然后更新插入到 MongoDB。输入名称采用

形式
<input type="text" name="Company.addressdata[a].city" />

其中“a”是列表中的索引。这一切都很好!地址对象列表在提交时创建并插入到 mongoDB。

但是,我刚刚添加了删除地址的功能,现在我遇到了麻烦。我注意到当用户删除第一行时,之后的所有行都丢失了。因此,如果他们删除 0 索引,Company 对象将不会填充地址列表,因此他们不会进入 MongoDB。

有没有办法解决这个问题?这是它的设计方式吗?用新索引重新编号以下所有行似乎太多了,但这就是它所需要的吗?还是有别的办法?

【问题讨论】:

    标签: c# asp.net-mvc mongodb


    【解决方案1】:

    根据我的经验,这是设计使然。索引必须从 0 开始,否则您必须使用特殊元素为每个索引定义自己的索引。

    这篇文章展示了一个例子:http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/

    <form method="post" action="/Home/Create">
    
        <input type="hidden" name="products.Index" value="cold" />
        <input type="text" name="products[cold].Name" value="Beer" />
        <input type="text" name="products[cold].Price" value="7.32" />
    
        <input type="hidden" name="products.Index" value="123" />
        <input type="text" name="products[123].Name" value="Chips" />
        <input type="text" name="products[123].Price" value="2.23" />
    
        <input type="hidden" name="products.Index" value="caliente" />
        <input type="text" name="products[caliente].Name" value="Salsa" />
        <input type="text" name="products[caliente].Price" value="1.23" />
    
        <input type="submit" />
    </form>
    

    所以你有两种选择:

    1. 删除时更新索引,或
    2. 定义任意索引

    【讨论】:

    • 太棒了!任意指数是要走的路。谢谢!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-19
    • 2014-10-04
    • 2019-09-18
    • 2018-03-31
    • 2020-10-02
    • 1970-01-01
    • 2012-03-15
    相关资源
    最近更新 更多