1

I have a view model that contains a single property:

public List<string> TeamNames = new List<string>();

The user is presented with a form that initially only contains a single textbox to enter the team name. However, the user has the ability to add another textbox through javascript in order to add another team name.

My question is - How can I bind these dynamic textboxes to my list in my view model?

The Vanilla Thrilla
  • 1,915
  • 10
  • 30
  • 49
  • Since you property is a collection of value types, you just need to generate `. For dynamically binding controls for collections of complex object, [this answer](http://stackoverflow.com/questions/28019793/submit-same-partial-view-called-multiple-times-data-to-controller/28081308#28081308) gives some options. –  Jul 27 '15 at 23:47

2 Answers2

0

Firstly, create a Hidden input on the form. Then use JQuery to create these textboxes. After all, just serialize data in this hidden field befure submitting data. Finally, just deserialise it on server side and do whatever you want.

For example on load

that.onLoad = function () {
    var listString = that.hidden.value;
    that.list = $.parseJSON(listString);
}

on submit:

function updateHidden() {
    that.hidden.value = JSON.stringify(that.list);
}
Alex Zhukovskiy
  • 9,565
  • 11
  • 75
  • 151
0

If your initial list is empty and it's to be dynamically clreated, you don't need to pass empty list to the view. here goes simplified version of what you need.

controller:

public class TestController : Controller
{
    // GET: Test
    public ActionResult Index()
    {
        return View();
    }

    [HttpGet]
    public ActionResult AddTeams()
    {
        // you do not need to pass anything if you list is empty
        return View();
    }

    [HttpPost]
    public ActionResult AddTeams(List<string> teamNames)
    {
        // do whatever you want with your teamnames

        return RedirectToAction("Index");
    }
}

view:

@using (Html.BeginForm("AddTeams", "Test", FormMethod.Post))
{
    <table id="teams-list">
        <tr>
            <td>Team name:</td>
            <td><input type="text" name="teamNames[0]" /></td>
        </tr>
    </table>

    <button type="button" id="add-btn">Add one more team</button>

    <br/>

    <button type="submit">submit</button>
}

<script>
    $('#add-btn').on('click', function() {
        var currentTeamCount = $('#teams-list tr').length;

        $('#teams-list  tr:last').after('<tr><td>Team name:</td><td><input type="text" name="teamNames[' + currentTeamCount + ']" /></td></tr>');
    });
</script>
t3mplar
  • 525
  • 6
  • 13