My model is simple, one client can have many phone numbers :
I have represented this in Entity Framework
You have to do a few things:
First create a ViewModel
that has the properties you need:
public class ClientViewModel
{
public int Id {get;set;}
public string Name {get;set;}
public PhoneNumber PhoneNumber1 {get;set;}
public PhoneNumber PhoneNumber2 {get;set;}
}
Change Create
to return the ClientViewModel
[HttpGet]
public ActionResult Create()
{
return View(new ClientViewModel());
}
Map the HttpPost
to use the ClientViewModel
and map the values to it:
[HttpPost]
public ActionResult Create(ClientViewModel clientViewModel)
{
var client = new Client();
client.Name = clientViewModel.Name;
client.PhoneNumbers.Add(clientViewModel.PhoneNumber1);
client.PhoneNumbers.Add(clientViewModel.PhoneNumber2);
db.Clients.Add(client);
db.SaveChanges();
return RedirectToAction("Index", "Client");
}
Then, finally, modify your view:
<fieldset>
<legend>Client</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.PhoneNumber1.Number)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.PhoneNumber1.Number)
@Html.ValidationMessageFor(model => model.PhoneNumber1.Number)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.PhoneNumber2.Number)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.PhoneNumber2.Number)
@Html.ValidationMessageFor(model => model.PhoneNumber2.Number)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
For the collection you can use something like this:
@for(int i = 0; i < Model.PhoneNumbers.Count; i++)
{
<div class="editor-field">
@Html.EditorFor(model => model.PhoneNumbers[i])
@Html.ValidationMessageFor(model => model.PhoneNumbers[i])
</div>
}