1
votes

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?

3

3 Answers

1
votes

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.

0
votes

You can create dynamic control in MVC view and bind with your model. for Example, You can use list collection in your view model class or model class and can create dynamic control in view, it will be automatically bind with your model properties.

0
votes

If you know that there will be 5 phone numbers then you can try this example this will add 5 textbox and on submitting you will get the values in you view model

public class Book
{
    public string Title { get; set; }
    public string Author { get; set; }
    public DateTime DatePublished { get; set; }

}

public class BookViewModel
{
    public List<Book> Books { get; set; }

}

View

 @model MVCLearning.Models.BookViewModel

@{
  using (Html.BeginForm("Submit", "Dynamic"))
   {

    if (Model.Count > 0 && Model != null)
    {
        for (int i = 0; i < 5; i++)
        {
            <div id="div_@i">
                @Html.TextBoxFor(m => Model.Books[i].Title)
            </div>
        }
        <input type="submit" value="Submit" />

    }

}
}