model binding of non-sequential arrays

Posted by user281180 on Stack Overflow See other posts from Stack Overflow or by user281180
Published on 2010-06-16T09:51:49Z Indexed on 2010/06/16 9:52 UTC
Read the original article Hit count: 195

Filed under:

I am having a table in which i`m dynamically creating and deleting rows. How can I change the code such that the rows be added and deleted and the model info property filled accordingly.

Bearing in mind that the rows can be dynamically created and deleted, I may have Info[0], Inf0[3], info[4]... My objective is to be able to bind the array even if it`s not in sequence.

Model

public class Person
    {
        public int[] Size { get; set; }
        public string[] Name { get; set; }
        public Info[]info { get; set; }
    }

    public class Info
    {
        public string Address { get; set; }
        public string Tel { get; set; }

View

    <script type="text/javascript" language="javascript">
        $(function () {

            var count = 1;

            $('#AddSize').live('click', function () {
                $("#divSize").append('</br><input type="text" id="Size" name="Size" value=""/><input type = "button" id="AddSize" value="Add"/>');

            });

            $('#AddName').live('click', function () {
                $("#divName").append('</br><input type="text" id="Name" name="Name" value=""/><input type = "button"  id="AddName" value="Add"/>');

            });

            $('#AddRow').live('click', function () {
                $('#details').append('<tr><td>Address</td><td> <input type="text"  name="Info[' + count + '].Address"/></td><td>Tel</td><td><input type="text"  name="Info[' + count++ + '].Tel"/></td> <td><input type="button" id="AddRow" value="Add"/> </td></tr>');
            });




        });        
       </script>
</head>

<body>
  <form id="closeForm" action="<%=Url.Action("Create",new{Action="Create"}) %>" method="post" enctype="multipart/form-data">
    <div id="divSize">
    <input type="text" name="Size"  value=""/> <input type="button" value="Add" id="AddSize" />
    </div>


    <div id="divName">
    <input type="text" name="Name"  value=""/> <input type="button" value="Add" id="AddName" />
    </div>


    <div id="Tab">
    <table id="details">
       <tr><td>Address</td><td> <input type="text"  name="Info[0].Address"/></td><td>Tel</td><td><input type="text"  name="Info[0].Tel"/></td> <td><input type="button" id="AddRow" value="Add"/> </td></tr>
    </table>

    </div>

    <input type="submit" value="Submit" />
    </form>


</body>
 }

Controller

public ActionResult Create(Person person)
        {
            return new EmptyResult();
        }

© Stack Overflow or respective owner

Related posts about asp.net-mvc