0

I'm developing a "Create" view for adding a new Person record in the database. In addition to displaying entry fields for Person, the view also needs to allow user to add one or more of Addresses. For example, this is the simplified entity relationship:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public IEnumerable<Address> Addresses { get; set; }
}

public class Address
{
    public string Street{ get; set; }
    public string City { get; set; }
    public string State { get; set; }
}

I know I can do something like this using Razor views:

In the main view Views\Person\Create.cshtml:

@model Person
@Html.TextBoxFor(model => model.FirstName)
@Html.TextBoxFor(model => model.LastName)
@Html.EditorFor(model => model.Addresses)

And then in Views\Person\EditorTemplates\Address.cshtml:

@model Address
@Html.TextBoxFor(model => model.Street)
@Html.TextBoxFor(model => model.City)
@Html.TextBoxFor(model => model.State)

But this works well when you're feeding it a populated list of addresses (like maybe in EditPerson view). But I'm not sure how to work with this in the CREATE situation, because the number of addresses is unknown. I guess I could use jquery to generate a new row of input textboxes with careful naming for NAME attribute, but that seems messy.

Anybody worked with submitting a form with one-to-many relationships like this?

Jiveman
  • 1,022
  • 1
  • 13
  • 30
  • 1
    Yes, you may use client side script to dynamically add form elements. [Here is a sample post](http://stackoverflow.com/questions/39106531/strongly-typed-view-for-model-class-with-collection). If you do not prefer client side code, when user wants to add a new row, you can post back to server and server can add one more item in the collection and return the view back and you can use the editor template solution. – Shyju Sep 12 '16 at 02:44
  • 1
    Refer [this answer](http://stackoverflow.com/questions/28019793/submit-same-partial-view-called-multiple-times-data-to-controller/28081308#28081308) for some options to dynamically add (and delete) collection items –  Sep 12 '16 at 02:45

0 Answers0