Reputation: 85
I would like to display a form that lets a user enter up to 10 rows of information. If they need to go over, I'm going to use an "add additional row" button that will add one row at a time. What will my Model class look like for something like this? When I use javascript to add a new row, how can I tie that new row into the Model as well?
Upvotes: 1
Views: 1059
Reputation: 1038930
You may take a look at the following blog post which explains how to achieve exactly that. It uses a custom helper (Html.BeginCollectionItem
) which allows to use non sequential as collection indexes instead of numbers which makes adding/deleting new items much easier.
Upvotes: 0
Reputation: 4159
Probably this rows contains related values, so you can give the same name to all theses inputs in the html, and declare that you action receive an array of values.
Assume that you have this
<form method="post" action="/Controller/YourAction">
<input type="text" name="row" value="1" />
<input type="text" name="row" value="2" />
<input type="text" name="row" value="3" />
<input type="text" name="row" value="4" />
<input type="text" name="row" value="5" />
<input type="text" name="row" value="6" />
<input type="submit" />
</form>
all that you need to do is declare this inside your Controller
public ActionResult YourAction(int[] row)
{
//put your code here
}
and you will have all the values inside the row array
Upvotes: 0
Reputation: 28844
This article from Phil Haack shows you how to bind to collections. You'll need to use the javascript to create the new row with the correct names.
Upvotes: 1