How to update a List in a View und refresh the View with the updated List in ASP.NET?

Christopher H 0 Reputation points
2024-06-07T10:51:09.9333333+00:00

In my Controller I read data from a Excelfile and compare this data with data from the database see:

  `[HttpPost]`
      public ActionResult UploadWöchentlichesUpdate(IFormFile excelFile)
      {
          if (excelFile != null && excelFile.Length > 0)
          {
              string path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/uploads", excelFile.FileName);
              try
              {
                  using (var stream = new FileStream(path, FileMode.Create))
                  {
                      excelFile.CopyTo(stream);
                  }
                  List<int> columnNumbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 };
                  System.Data.DataTable dataTable = ConvertExcelToDataTable(path, 1, columnNumbers);
                  if (System.IO.File.Exists(path))
                  {
                      System.IO.File.Delete(path);
                  }
                  List<PersonChangeViewModel> personenChanged = new List<PersonChangeViewModel>();
                  foreach (DataRow row in dataTable.Rows)
                  {
                      object geburtsdatumValue = row["Geb.-Datum"];
                      DateTime geburtsdatum;
                      if (geburtsdatumValue != null && decimal.TryParse(geburtsdatumValue.ToString(), out decimal geburtsdatumDecimal) && !geburtsdatumValue.ToString().StartsWith("00.00"))
                      {
                          geburtsdatum = DateTime.FromOADate(Convert.ToDouble(geburtsdatumValue));
                      }
                      else
                      {
                          continue;
                      }
                      string titel = row["Titel"].ToString();
                      string rufname = row["Rufname"].ToString();
                      string nachname = row["Nachname"].ToString();
                      string geschlecht = row["Geschlecht"].ToString();
                      string straße = row["Straße"].ToString();
                      string hausnr = row["Hausnr."].ToString();
                      string buchstabenzusatz = row["Buchstabenzus."].ToString();
                      string adresszusatz = row["Adresszus."].ToString();
                      string plz = row["PLZ"].ToString();
                      string ortsname = row["Ortsname"].ToString();
                      var bezirik = _context.Stadtbezirk.SingleOrDefault(x => x.Name.Equals(row["Ortsteil"].ToString()));
                      var merkmal = _context.Merkmal.SingleOrDefault(x => x.Merkmalbeschreibung.Equals("keins"));
                      string sterbedatum = row["Sterbedatum"].ToString();
                      string einzugsdatum = row["Einzugsdatum"].ToString();
                      var person = _context.Person.SingleOrDefault(x => x.Rufname.Equals(rufname) && x.Nachname.Equals(nachname));
                      var personChangeViewModel = new PersonChangeViewModel
                      {
                          OldPerson = person,
                          NewPerson = new Person
                          {
                              Titel = titel,
                              Nachname = nachname,
                              Rufname = rufname,
                              Geburtsdatum = geburtsdatum,
                              Geschlecht = geschlecht,
                              Straße = straße,
                              Hausnr = hausnr,
                              Buchstabenzusatz = buchstabenzusatz,
                              Adresszusatz = adresszusatz,
                              PLZ = plz,
                              Ortsname = ortsname,
                              BezirksID = bezirik?.ID ?? 11,
                              Stadtbezirk = bezirik,
                              MerkmalID = merkmal.ID,
                              Merkmal = merkmal
                           
                          }
                      };
                      if (!string.IsNullOrEmpty(sterbedatum))
                      {
                          merkmal = _context.Merkmal.SingleOrDefault(x => x.Merkmalbeschreibung.Equals("verstorben"));
                          personChangeViewModel.NewPerson.MerkmalID = merkmal.ID;
                          personChangeViewModel.NewPerson.Merkmal = merkmal;
                          if (person != null)
                          {
                              personChangeViewModel.NewPerson.Straße = person.Straße;
                              personChangeViewModel.NewPerson.Hausnr = person.Hausnr;
                              personChangeViewModel.NewPerson.Buchstabenzusatz = person.Buchstabenzusatz;
                              personChangeViewModel.NewPerson.Adresszusatz = person.Adresszusatz;
                              personChangeViewModel.NewPerson.PLZ = person.PLZ;
                              personChangeViewModel.NewPerson.Ortsname = person.Ortsname;
                              personChangeViewModel.NewPerson.BezirksID = person.BezirksID;
                              personChangeViewModel.NewPerson.Stadtbezirk = person.Stadtbezirk;
                          }
                          else
                          {
                              personChangeViewModel.NewPerson.Straße = "unbekannt";
                              personChangeViewModel.NewPerson.Hausnr = "0";
                              personChangeViewModel.NewPerson.PLZ = "00000";
                              personChangeViewModel.NewPerson.Ortsname = "unbekannt";
                              personChangeViewModel.NewPerson.BezirksID = 11;
                          }
                      }
                      personenChanged.Add(personChangeViewModel);
                  }
                  return View("ConfirmChanges", personenChanged);
              }
              catch (Exception ex)
              {
                  // Log the exception and return error message
                  ViewBag.Message = "Error: " + ex.Message;
                  return View();
              }
          }
          ViewBag.Message = "Please select an Excel file.";
          return View();
      }

Here is the View I create with the List personenChanged:

@model IEnumerable<Alters_Ehejubiläen_Weihnachtsbriefe_Ehrenpatenschaften.Models.PersonChangeViewModel>
@{
    ViewData["Title"] = "Bestätigen Sie die Änderungen";
}
<h2>@ViewData["Title"]</h2>
    @foreach (var item in Model)
    {
    <form asp-action="ConfirmChanges" method="post">
     
        <div>
            @if (item.OldPerson != null)
            {
                <h3>Alte Daten</h3>
                <p>Titel: @item.OldPerson.Titel</p>
                <p>Rufname: @item.OldPerson.Rufname</p>
                <p>Nachname: @item.OldPerson.Nachname</p>
                <p>Straße: @item.OldPerson.Straße</p>
                <p>Hausnr: @item.OldPerson.Hausnr</p>
                <p>PLZ: @item.OldPerson.PLZ</p>
                <p>Ortsname: @item.OldPerson.Ortsname</p>
                <p>Merkmal: @item.OldPerson.Merkmal.Merkmalbeschreibung</p>
            }
            else
            {
                <h3>Neue Person</h3>
                <p>Es gibt keine bestehenden Daten für diese Person. Eine neue Person wird erstellt.</p>
            }
            <h3>Neue Daten</h3>
            <p>Titel: @item.NewPerson.Titel</p>
            <p>Rufname: @item.NewPerson.Rufname</p>
            <p>Nachname: @item.NewPerson.Nachname</p>
            <p>Straße: @item.NewPerson.Straße</p>
            <p>Hausnr: @item.NewPerson.Hausnr</p>
            <p>PLZ: @item.NewPerson.PLZ</p>
            <p>Ortsname: @item.NewPerson.Ortsname</p>
            <p>Merkmal: @item.NewPerson.Merkmal.Merkmalbeschreibung</p>
            <input type="hidden" name="personId" value="@(item.OldPerson?.ID ?? 0)" />
            <input type="hidden" name="newTitel" value="@item.NewPerson.Titel" />
            <input type="hidden" name="newRufname" value="@item.NewPerson.Rufname" />
            <input type="hidden" name="newNachname" value="@item.NewPerson.Nachname" />
            <input type="hidden" name="newStraße" value="@item.NewPerson.Straße" />
            <input type="hidden" name="newHausnr" value="@item.NewPerson.Hausnr" />
            <input type="hidden" name="newBuchstabenzusatz" value="@item.NewPerson.Buchstabenzusatz" />
            <input type="hidden" name="newAdresszusatz" value="@item.NewPerson.Adresszusatz" />
            <input type="hidden" name="newPLZ" value="@item.NewPerson.PLZ" />
            <input type="hidden" name="newOrtsname" value="@item.NewPerson.Ortsname" />
            <input type="hidden" name="newBezirksID" value="@item.NewPerson.BezirksID" />
            <input type="hidden" name="newMerkmalID" value="@item.NewPerson.MerkmalID" />
            <button type="submit" name="action" value="confirm">Bestätigen</button>
            <button type="submit" name="action" value="reject">Änderung verwerfen</button>
        </div>
    </form>
    }

I want to change the data of the confirmed form in the database if the user clicks on the button with the value "confirm" and the reload the view with all values except the values from the confirmed form. If the user clicks the button with the value "reject" I want to change nothing in the database and reload the view without the data from the confirmed form. So I made this controller function:

  `[HttpPost]`
        public ActionResult ConfirmChanges(string action, int personId, string newTitel, string newRufname, string newNachname, string newStraße, string newHausnr, string newBuchstabenzusatz, string newAdresszusatz, string newPLZ, string newOrtsname, int? newBezirksID, int? newMerkmalID)
        {
            if (action == "confirm")
            {
                Person person;
                if (personId == 0) // Neue Person
                {
                    person = new Person
                    {
                        Titel = newTitel,
                        Rufname = newRufname,
                        Nachname = newNachname,
                        Straße = newStraße,
                        Hausnr = newHausnr,
                        Buchstabenzusatz = newBuchstabenzusatz,
                        Adresszusatz = newAdresszusatz,
                        PLZ = newPLZ,
                        Ortsname = newOrtsname,
                        BezirksID = (int)newBezirksID,
                        MerkmalID = (int)newMerkmalID
                    };
                    _context.Person.Add(person);
                }
                else // Bestehende Person aktualisieren
                {
                    person = _context.Person.SingleOrDefault(p => p.ID == personId);
                    if (person == null)
                    {
                        ViewBag.Message = "Person not found.";
                        return View("ConfirmChanges");
                    }
                    person.Titel = newTitel;
                    person.Rufname = newRufname;
                    person.Nachname = newNachname;
                    person.Straße = newStraße;
                    person.Hausnr = newHausnr;
                    person.Buchstabenzusatz = newBuchstabenzusatz;
                    person.Adresszusatz = newAdresszusatz;
                    person.PLZ = newPLZ;
                    person.Ortsname = newOrtsname;
                    person.BezirksID = (int)newBezirksID;
                    person.MerkmalID = (int)newMerkmalID;
                }
                _context.SaveChanges();
            }
            // If action is "reject", no changes are made to the person in the database
            return View("ConfirmChanges"); // Redirect to an appropriate action after processing
        }

The problem is that I think you can not send the hole list from the view to the controller function ConfirmChanges. So I can not show the view again with all the data just without the data from the form with is confirmed or rejected. It is just working for the data of one form in the view but the controller function ConfirmChanges can not recread the view with the list of PersonChangedViewModel with all the data except of the confirmed or rejected form.

How can I solve this?

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,393 questions
{count} votes