C# – Dynamic Controls in a Strongly Typed View (ASP.NET MVC)

asp.net-mvccmodel-view-controller

Say i have the following:

public class Person{
    public int ID {get; set;}
    public string Name {get; set;}
}

public class Phone{
    public int ID {get; set;}
    public string PhoneNumber {get; set;}
}

public Class AddEditViewModel{
    public Person MyPerson{get; set;}
    public List MyPhones{get; set;}
}

I want to create a create/edit action in my MVC app – the page inherits from

ViewPage<AddEditViewModel>

and i want to be able to dynamically add the fields for the end-user to add a "phone" (anywhere between 0 – 5 phones). How would i pass that data to the Create/Edit method in my controller. I have tried the following, but nothing seems to get the phone numbers.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(AddEditViewModel data){} 

with this i can call data.MyPerson.Name and get the value but data.MyPhones == null

My question would be: how would one set up the view and controller to be able to submit a single add/edit page that creates a single person object with multiple phone objects given the code above?

Best Answer

If I understand your question correctly you are asking about binding to a list of phone numbers. Phil Haack has a post of how to do model binding to a list

Hope this helps.