代码之家  ›  专栏  ›  技术社区  ›  TJB

如何在ASP.net MVC中使用jQuery替换复杂类型子集合的所有id属性

  •  0
  • TJB  · 技术社区  · 16 年前

    <div class="childContainer" >
       <!-- There's one of these for each property for each child collection item -->
       <%= Html.TextBox("ChildCollectionName[0].ChildPropertyName", /* blah blah */ ) %>
       <%= Html.TextBox("ChildCollectionName[0].OtherChildPropertyName", /* blah blah */ ) %>
       <!-- ... -->
    </div>
    

    这将被渲染为

    <div class="childContainer" >
        <input id="ChildCollectionName[0]_ChildPropertyName" ... />
        <input id="ChildCollectionName[0]_OtherChildPropertyName" ... />
    ...
    </div>
    <div class="childContainer" >
        <input id="ChildCollectionName[1]_ChildPropertyName" ... />
        <input id="ChildCollectionName[1]_OtherChildPropertyName" ... />
    ...
    </div>
    

    对于chlid集合中的每个条目。

    这个集合是使用jQuery在表单中动态创建的,因此可以添加、删除条目等。每当集合上有操作时,我都需要更新索引,以便它在服务器端正确绑定。

    全部替换[*]-->[N] 其中N是正确的索引。

    另外,如果你有一个更容易的方法来确定儿童收藏,我会采取任何建议,以及。

    唐克斯!

    2 回复  |  直到 16 年前
        1
  •  1
  •   Community Mohan Dere    9 年前

    我也做过类似的事情,在视图中使用模型对象的动态列表。我在表单中使用了表结构,但我相信您也可以应用类似的逻辑。

    我使用了添加/删除表行的按钮。提交表格时必须保持数字顺序,因此id应为0,1,2,3,不能为0,2,3,4等。我的设计更简单,您只能在列表底部添加一项,而只能删除列表中的最后一项。因此,我可以保持身份证的秩序。

    $('.add').live('click', function()
    {
        var addRowId = $('#myTable tr').length;
        var internalId = addRowId - 1; //subtract -1 for header row
    
        //clone the last row
        var row = $('#ft tr:last').clone(false);
    
        //modify the input id and name values
        row.find(':input')
            .attr('id', function() { return 
                $(this).attr('id').replace(/\[[\d+]\]/g, '[' + internalId + ']');
            })
            .attr('name', function() { return 
                $(this).attr('name').replace(/\[[\d+]\]/g, '[' + internalId + ']');
            });
    
        //add the new row
        $('#ft tr:last').after(row);
    
        return false;
    });
    

    注:

    ASP.NET-MVC2 Preview 1: Are There Any Breaking Changes?

        2
  •  0
  •   Çağdaş Tekin    16 年前

    不必每次集合更改时都操作DOM元素,您可以将元素数组保存在JavaScript变量中,并在需要添加/删除元素时直接使用该数组。然后使用数组重新渲染输入元素。