Note that there are some explanatory texts on larger screens.

plurals
  1. POMVC .NET Model Binding to Array on the fly
    primarykey
    data
    text
    <p>In Scotts blog <a href="http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx" rel="nofollow">post</a> he describes how to post an array of objects to the controller.</p> <p><strong>My Question</strong> how best to generate a View for this that allows the user to add more array items on the fly?</p> <p>If I write</p> <pre><code> foreach(MyModel item in Model) { &lt;p&gt;@Html.TextBoxFor(m =&gt; item.Name)&lt;/p&gt; } </code></pre> <p>and have the controller add a new item to the array each time it generates <code>&lt;input type="text" name="item.Name" /&gt;</code> missing the <a href="http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx" rel="nofollow">1</a> Array index.</p> <p>If I hand code the <code>&lt;input&gt;</code> then it works but I lose all the client side validation attributes like <code>data-val-required="Name is required"</code></p> <p>What I want to be able to do is have the User add new Items to the array on the fly and still retain unobtrusive validation?. What's the best practice for this? </p> <p>I am thinking I have write it myself using jQuery but if so can I keep the validation?</p> <p><strong>Update</strong> Seems like Tassadaque answer is a nice .NET solution but looks like a lot of server side code to do something which should be very easy. Muhammad Adeel Zahi answer is ok but still misses out client side validation.</p> <p>I think I will end up just writing my own client side HTML manually and using jQuery live and validation plug-in. So I can do all my own validation and adding and removing of new Items all client side without any calls to the server. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload