Bitz
Bitz

Reputation: 1148

Sending dynamically generated textbox values to C# Controller?

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

Answers (1)

Georg Patscheider
Georg Patscheider

Reputation: 9463

The MVC Modelbinder will be able to directly bind the POST data if you meet some conditions:

  • The name and id of the dynamically added HTML inputs conform to the naming scheme used by MVC. I.e. to bind the first element of a collection, the value of the html id attribute should be {collectionName}_0 and the value of the name attribute should be {collectionName}[0]
  • The ViewModel contains collections to which the list of inputs can be bound.

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 idand 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

Related Questions