0

I have a form of contact info as follows:

Name: input    Email : input
Add More

if the user want to add another Name and Email, she can click on Add More and she will see another set of Name and email input boxes.

How do you handle this with MVC at controller side?

public ActionResult Process(IEnumerable<Contact> contacts){
.... ???

or If i need a model binding, how can i get this done, what should my model be?

DarthVader
  • 52,984
  • 76
  • 209
  • 300
  • Whats wrong with your proposed solution? A IEnumerable and Contact being a class with the properties Name and Email. That takes care of model binding as well. – Alex Jun 12 '13 at 10:58
  • @Alex depends on how the client control are created. We need more info – Dave Hogan Jun 12 '13 at 11:00
  • @DaveHogan I was assuming he is using Razor and indexes his dynamic controls accordingly ( [0].Name, [0].Email, [1].Name, [1].Email etc.. ) – Alex Jun 12 '13 at 11:04

2 Answers2

1

It depends on many factors such as how you're creating the fields. This is quite a generic question.

I would personally do this by building a json string and sending to the server.

Another approach is by building the elements up on the client in a specific way for model binding to know it's a collection.

I quote @Shyju who helped me with a similar question.

To keep your Model binding works with the newly added dynamic elements, you need to follow the naming convention of the elements.

The trick is to keep the id property value of the html element in this format. CollectionName_ItemIndex__PropertyName

and name property value in this format

CollectionName[ItemIndex].PropertyName

Community
  • 1
  • 1
Dave Hogan
  • 3,201
  • 6
  • 29
  • 54
0

I think I would use some

IList<Contact> Contacts; as a ViewModel. 

After submit a form some action would handle with that. From the view perspective I would use jQuery append() method to add next contact row and to not make a full webiste refresh.

Piotr Czarnecki
  • 1,688
  • 3
  • 14
  • 22