MVC “create view” when there is one to many relationship in model

后端 未结 2 773
谎友^
谎友^ 2021-01-01 08:01

My model is simple, one client can have many phone numbers :

I have represented this in Entity Framework\"\"

2条回答
  •  长情又很酷
    2021-01-01 08:19

    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:

    Client
    @Html.LabelFor(model => model.Name)
    @Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name)
    @Html.LabelFor(model => model.PhoneNumber1.Number)
    @Html.EditorFor(model => model.PhoneNumber1.Number) @Html.ValidationMessageFor(model => model.PhoneNumber1.Number)
    @Html.LabelFor(model => model.PhoneNumber2.Number)
    @Html.EditorFor(model => model.PhoneNumber2.Number) @Html.ValidationMessageFor(model => model.PhoneNumber2.Number)

提交回复
热议问题