ASP.NET MVC4 dynamic form generation

后端 未结 3 1672
说谎
说谎 2021-01-01 05:26

I am new to ASP.NET MVC and need some help. I have a need to create a form where the form is dynamically created. For example let\'s say I have a model named Person. The

相关标签:
3条回答
  • 2021-01-01 06:13

    Phil Haack wrote an article on pretty much what you want to do. To have it be dynamic (meaning they can 1 to many people to the list), you'll have to do some JavaScript manipulation by attaching a click event to the add button to copy a new row of the input fields. I first suggest reading through that article first to understand how you need to structure the input fields so that when you post back the list gets populated.

    0 讨论(0)
  • 2021-01-01 06:30

    Steven Sanderson, in his blog, has a very nice article about this... it is not relying in numeric indexes for each person to avoid "holes" when removing one in the middle.

    See the article here: http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/

    Then, you will need validation: http://blog.stevensanderson.com/2010/01/28/validating-a-variable-length-list-aspnet-mvc-2-style/

    I'm using this code in MVC 3 and 4... and it works like a charm.

    0 讨论(0)
  • 2021-01-01 06:31

    There is no need for multiple POSTs. You want your form to send an array of Person to your action. The action will be something like

    [HttpPost]
    public ActionResult AddPeople(Person[] people){ ... }
    

    To achieve that, you must enumerate the input fields on your view. They must be indexed, starting in 0 and incrementing accordingly, like:

    @using(Html.BeginForm("AddPeople","TheController", FormMethod.Post))
    {
      <input type="text" name="people[0].FirstName" />
      <input type="text" name="people[0].LastName" />
      ...
      <input type="text" name="people[1].FirstName" />
      <input type="text" name="people[1].LastName" />
      ...
      <input type="text" name="people[n].FirstName" />
      <input type="text" name="people[n].LastName" />
    }
    

    You must add the new fields using javascript, with a simple DOM manipulation. Just remember to keep the indexes in order.

    0 讨论(0)
提交回复
热议问题