-1

My Model

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

My Controller

public class PersonController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
    [HttpPost]
    public ActionResult Save(Person[] people)
    {
        foreach (var p in people)
            // Do Something
        return View();
    }
}

My View

@using (Html.BeginForm("Save", "Person", FormMethod.Post))

{

<div id="form"></div>

<button type="button" class="btn btn-info" id="addItem">New Person</button>
<button type="submit" class="btn btn-success">Salvar</button>

}

My Script

<script type="text/javascript">

        $(document).ready(function () {
            $("#addItem").click(addField);
            addField(); 
        });

        function addField() {
            var html = "Name: <input type='text' name='people[]' />";
            $("#form").append(html);
        }
</script>

I need to post the inserted data from forms to controller, but dont work... how can i do that?

i read about binding to model arrays and i did this above.

Leonardo
  • 1
  • 4

1 Answers1

0

you can use Ajax us will need to change your Form from pOst to allow JQuery to do this use $('#Form').Serialize() to get all your data and it should convert into teh C# list of Person if that does not work try to manually create the object and post it

 $.ajax({
            url: URL + 'Person/Save',
            type: 'POST',

            data:  $('#Form').Serialize()

            success: function (data) {
            },

            error: function (e, data) {
            }
        });
China Syndrome
  • 953
  • 12
  • 24
  • i did with this @Html.TextBox("Person[0].Name").. But i cant put this HtmlHelper inside of my var html like: var html = @Html.TextBox("Person[0].Name") When i press the button to add this new textbox, nothing happens... How can i create Html.TextBox Dynamically? – Leonardo Sep 24 '18 at 17:32
  • its corret this: var html = "Name: "; i only forgot people[0] thks for your time :) – Leonardo Sep 24 '18 at 17:57