0

I need to update a company class with an IList of addresses. These are my Data Models.

// Entity class Company — managed by Nhibernate
public class Company
{
  public virtual IList<Address> _addresses { get; set; }

  public Company()
  {
    _addresses = new List<Address>();
  }
}

// Entity class Address — managed by Nhibernate
public class Address
{
  public virtual string line1 { get; set; }
  public virtual string line1 { get; set; }
}

I am packing the data from the Entity class to the Viewmodel in the controller's GET action, and I am unpacking the data from the Viewmodel back to the Entity class in the controller's POST action.

Here are my View Models.

// Class CompanyRequest
public class CompanyRequest
{
  public IList<AddressRequest> AddressRequests;
}

//Class AddressRequests
public class AddressRequest
{
  public string line1 { get; set; }
  public string line1 { get; set; }
}

I am using a partial view to display each address box. For each AddressRequest in AddressRequests I pass the object to a partial view with the prefix set correctly.

for(var i = 0 ; i < AddressRequests.Count() ; i++)
{
  ViewData["Prefeix"] = String.Format("AddressRequests[{0}]", i);
  Html.RenderPartial("_addressPartial", AddressRequests[i]);
}

I need to be able to add an "Add New Address" button so that the user can add a new address to this list. This has to be done WITHOUT refreshing the page. When the user clicks that button, another address-box (same partial, I'm guessing) appears. Then the user edits the box and presses a "Save" button. This Save button is supposed to save the whole Company data, not just the Address.

Is there a way to do this? Any help is greatly appreciated!

1 Answers1

1

The answer is that you use a client-side technology i.e. javascript to dynamically load additional addresses in the UI, then pass the data back to the server side for processing via ajax techniques when they are ready to save.

There are plenty of javascript libraries out there that can perform ajax requests. I prefer the jQuery library.

Here are a number of articles on how to perform ajax with mvc:

And of course: http://bit.ly/XWYE5P

Community
  • 1
  • 1
Matthew Cox
  • 13,566
  • 9
  • 54
  • 72
  • Really lame, just discovered that stackoverflow doesn't allow you to post links to the Let Me Google That For You website. Oh well – Matthew Cox Apr 03 '13 at 07:15
  • Ah ha! Found a workaround leveraging a url compressor =P It lives on! http://bit.ly/XWYE5P – Matthew Cox Apr 03 '13 at 07:56
  • Figured it out. All I had to do was to use an AJAX link to hit a controller action asynchronously. Will post my entire code shortly, because I think not everywhere you see this done **without** jQuery. – Chameera Dedduwage Apr 08 '13 at 11:06
  • @ChameeraDedduwage If you feel that my ajax answer was helpful and lead to the solution feel free to mark this as the answer. =P – Matthew Cox Apr 08 '13 at 19:14