Reputation: 1148
So I have a table that works like this: https://gfycat.com/WeakBlueIslandwhistler
Generated by:
<table class="table table-bordered table-with-button table-condensed " id="hidTable">
<thead>
<tr>
<th>HID #</th>
<th>Lines</th>
</tr>
</thead>
@for (int j = 0; j < 3; j++)
{
<tr>
<td>
<input class="form-control table-with-button" type="number" placeholder="HID" id="hid-@j">
</td>
<td>
<input class="form-control table-with-button" type="number" placeholder="Lines" id="lines-@j">
</td>
</tr>
}
</table>
New rows and textboxes are created by calling a javascript method.
Essentially, there are an unknown number of pairs of text fields in this table, and the data pairs need to be passed to the controller... (I'm thinking storing it as an object in tempdata?)
Each textbox has a unique id (hid-1, hid-2 hid-3 and lines-1, lines-2, lines-3 respectively)
What is the best way to iterate over these textboxes, save their value (I can handle validation prior to saving) and then pass it to the backend?
Upvotes: 2
Views: 1321
Reputation: 9463
The MVC Modelbinder will be able to directly bind the POST data if you meet some conditions:
id
attribute should be {collectionName}_0
and the value of the name
attribute should be {collectionName}[0]
So in your case, define a ViewModel that contains lists for HIDs and Lines
public class PostDataModel {
public ICollection<int> Hids { get; set; }
public ICollection<int> Lines { get; set; }
}
Then make sure that the javascript code that adds additional lines sets id
and name
correctly.
The generated inputs for the 0th line should look like this:
<input class="form-control table-with-button" type="number" placeholder="HID" id="Hids_0" name="Hids[0]">
<input class="form-control table-with-button" type="number" placeholder="Lines" id="Lines_0" name="Lines[0]">
If the User can delete any line before sumbitting, watch out for non sequential indices!
Then just submit the form with a normal POST and correlate HIDs and Lines using their index.
Upvotes: 2