CidaoPapito
CidaoPapito

Reputation: 612

MVC 4 create a form with a list as a property of my new object

I'm creating a form for register new users, each user is allowed to have many address. (many address to one user). I found this article but doesn't look right for me, because I have a main property which is user and the address has to be related with it. I would like to create something similar for add many address even in the create screen for new user, which doesn't exist the user primary key for these address be related.

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

Could someone send an example how is the better way to do it?

this is something very close to my code:

public class Person{
   public int PersonId { get; set; }
   public string Name { get; set; }      
   public virtual ICollection<Address> Addresses { get; set; }
}    
public class Address{
   public int AddressId { get; set; }
   public string Street { get; set; }      

   [ScriptIgnore]
   public virtual Person Person { get; set; }
}

Upvotes: 0

Views: 2533

Answers (2)

user3559349
user3559349

Reputation:

As Klors indicated, create a view models for Address and Person (suggest List<AddressVM> is initialized in PersonVM constructor). In your PersonController

[HttpGet]
public ActionResult Create()
{
  PersonVM model = new PersonVM();
  model.Addresses.Add(new AddressVM()); // add an empty address assuming at least one required
  return View(model, "Edit")
}

[HttpGet]
public ActionResult Edit(int ID)
{
  PersonVM model = // get from database/repository
  // If Address.Count == 0, add new Address
  return View(model);
}

[HttpPost]
public ActionResult Edit(PersonVM model)
{
  ...

In your view

@model PersonVM
@using (Html.BeginForm("Edit", "Person") {
  ....
  @Html.HiddenFor(m => m.ID)
  @Html.TextBoxFor(m => m.Name)
  ... 
  @Html.EditorFor(m => m.Addresses) // you may want to create an editor template for AddressVM
  <button type="button" id="AddAddress">Add address</button>

The EditorFor() will generate HTML similar to this (note the indexer)

<input type="text" name="Address[0].Street" id="Address_0__Street" ..../>
<input type="text" name="Address[0].Suburb" id="Address_0__Suburb" ..../>

To dynamically add new addresses, you need to use JavaScript to generate similar HTML, but increment the indexer. If you use an editor template, you can wrap the Address controls in a container (say <div class="address">) which make them easy to select as per the script below

Script to dynamically add a new address

$('#AddAddress').click(function() {
  var addresses = $('.address');
  // Get the number of existing address
  var count = addresses.length;
  // Get the first address and clone it
  var clone = addresses.first().clone();
  // Update the index of the clone
  clone.html($(clone).html().replace(/\[0\]/g, '[' + count + ']'));
  clone.html($(clone).html().replace(/"_0__"/g, '_' + count + '__'));
  // Add to the DOM
  addresses.last().after(clone);
}

Note this will also clone the values from the first address, so you may want to reset some or all of them, for example (after its been added)

clone.find('input').val('');

If you're using @Html.ValidationMessageFor() methods, note that dynamically added elements will not be validated in the browser unless you parse the form. An example of how to do that can be found here: jquery.validate.unobtrusive not working with dynamic injected elements

Upvotes: 2

Klors
Klors

Reputation: 2674

Something like this might be closer to what you need. You'll need to imagine the checkboxes are collections of fields for entering your address.

However, if you create a ViewModel for Person that contains a list of ViewModels for Address, you can create strongly typed editor templates and display templates named the same as the ViewModels and they'll automatically be picked up if you use @Html.EditorFor and @Html.DisplayFor which makes working with one to many's easier.

If you had files like so -

~/Models/PersonViewModel.cs
~/Models/AddressViewModel.cs
~/Views/Person/Edit.cshtml
~/Views/Shared/DisplayTemplates/AddressViewModel.cshtml
~/Views/Shared/EditorTemplates/AddressViewModel.cshtml

and a person ViewModel a bit like

public class PersonViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    ...
    public List<AddressViewModel> Addresses { get; set; }
}

If you then have an edit view for person like

@model PersonViewModel

<div>
@using (Html.BeginForm("Edit", "Person", new {id = Model.Id}, FormMethod.Post))
{
    <div>
        @Html.EditorForModel()
    </div>
    <div>
        <p>@Html.DisplayNameFor(p => p.Addresses)</p>

        @Html.EditorFor(p => p.Addresses)
    </div>

    <p>
        <input type="submit" value="Save"/>
    </p>
}
</div>

then the editor template should get picked up for the AddressViewModel once for each entry in the list. You'll have to add in some Ajax to allow new addresses to be created like in your example link. As long as the template contains all the fields for the AddressViewModel to work, then your Edit POST controller should just receive a PersonViewModel back as it's parameter.

There are some parts missing from my example, but you should be able to fill in the blanks from tutorials.

Upvotes: 1

Related Questions