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

后端 未结 2 749
谎友^
谎友^ 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:

    <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>
    
    0 讨论(0)
  • 2021-01-01 08:23

    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>
    }
    
    0 讨论(0)
提交回复
热议问题