locked
ASP.NET Core 2.2 Razor Web App Update list data RRS feed

  • Question

  • User1518508822 posted

    I have person's contact list. I need to update person's contact details. So I have dynamic generated textboxes for contacts. I need the best practise for updating person's contact details in database.

    @for (var i = 0; i < Model.Person.Contacts.Count; i++)
    {
       <div class="col-md-7 mb-3">
           <input type="text" name="txtContactNumber" asp-for="Person.Contacts[i].ContactNumber" class="form-control" />
           <input type="text" name="txtContactId" asp-for="Person.Contacts[i].ContactId" class="form-control" />
       </div>
    }
    
    [BindProperty]
    public Person person { get; set; }
    
    [BindProperty]
    public string[] txtContactNumber { get; set; }
    
    [BindProperty]
    public string[] txtContactId { get; set; }
    List<Contact> contacts = new List<Contact>();
    
    foreach (var txtNumber in  txtContactNumber)
    {
       contacts.Add(new Contact { ContactId = ????, ContactNumber = txtNumber });
    }
    

    But how can I send contactId with this list. So what is the c# and asp.net core mechanism for sending and updating these data ?

    Monday, June 17, 2019 1:26 PM

Answers

  • User-854763662 posted

    Hi michale.p ,

    I  think that there is one-to-many relationship between Person model and Contact model like below:

    public class Person
    {
         public int Id { get; set; }
         public string Name { get; set; }
    
         public List<Contact> Contacts { get; set; }
    }
    
    public class Contact
    {
         public int ContactId { get; set; }
         public string ContactNumber { get; set; }
    
         public int PersonId { get; set; }
         [ForeignKey("PersonId")]
         public Person Person { get; set; }
    }

    If you want to update person's contact details in database , you could refer to the following code :

    1.Generates the id and name HTML attributes for the expression name specified in the asp-for attribute.

     @for (var i = 0; i < Model.Person.Contacts.Count; i++)
    {
          <div class="form-group">
               <input type="text" asp-for="Person.Contacts[i].ContactNumber" class="form-control" />
               <input type="text" asp-for="Person.Contacts[i].ContactId" class="form-control" />
          </div>
    }

    2. Two approaches to update the ContactList in Person

    [BindProperty]
    public Person Person { get; set; }
    
    //Upate one by one foreach (var contact in Person.Contacts) { _context.Contact.Update(contact); }
    // Or Update a list _context.Contact.UpdateRange(Person.Contacts);

    Best Regards ,

    Sherry

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 18, 2019 2:49 AM