Search code examples
c#asp.net-core-mvc.net-6.0

How to Edit a database row in C# and ASP.NET Core 6.0 MVC?


I'm new at MVC. Last project I used list and I am replacing them with a database.

Delete went well, but updating not soo well.

I looked online but hadn't had much luck. I took a few lines that I had, basically if all goes well I go to index if the changes weren't made the user would stay on index...

I stayed on index.

Nothing changed in database of course...

I don't know if it´s related but maybe it's on conflict to pass the ID value to the database that is a primary key, that would be weird since I only allow the user to change Name, Last Name and Birth date

Model class:

public partial class Person
{
       public int Id { get; set; }
       public string FirstName { get; set; } = null!;
       public string LastName { get; set; } = null!;
       public DateTime Birth { get; set; }
       public int Roles { get; set; }

       public virtual ICollection<ClassDetail> ClassDetails { get; set; } = new List<ClassDetail>();
       public virtual Role RolesNavigation { get; set; } = null!;
}

View:

@model WebApplication2.School_dbModels.Person

@{
    ViewData["Title"] = "Edit";
}

<h1>Edit</h1>

<h4>Person</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Edit">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <input type="hidden" asp-for="Id" />
            <div class="form-group">
                <label asp-for="FirstName" class="control-label">First Name</label>
                <input asp-for="FirstName" class="form-control" />
                <span asp-validation-for="FirstName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="LastName" class="control-label">Last Name</label>
                <input asp-for="LastName" class="form-control" />
                <span asp-validation-for="LastName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Birth" class="control-label">Birthday</label>
                <input asp-for="Birth" class="form-control"/>
                <span asp-validation-for="Birth" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Controller edit action method:

// GET: Students/Edit/5
[HttpGet]
public ActionResult Edit(int id)
{
    Person studentToEdit = db.People.Find(id);

    return View(studentToEdit);
}

// POST: Students/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Person studentToEdit)
{
    if (ModelState.IsValid)
    {
        Person student = db.People.Where(s => s.Id == studentToEdit.Id).First();
        student.FirstName = studentToEdit.FirstName;
        student.LastName = studentToEdit.LastName;
        student.Birth = studentToEdit.Birth;

        db.Entry(student).State = EntityState.Modified;

        db.SaveChanges();

        // Refresh the index page with updated data
        return RedirectToAction("Index");
    }

    return View(studentToEdit);
}

Solution

  • I guess your problem may be caused by invalid Roles,ClassDetails ,RolesNavigation , you can try to add ? manully to like:

    public int? Roles { get; set; }
    public virtual ICollection<ClassDetail> ? ClassDetails { get; set; } = new List<ClassDetail>();
      
    public virtual Role? RolesNavigation { get; set; } = null!;
    

    or: you can remove <Nullable>enable</Nullable> from your project file (double-click the project name or right-click the project to choose Edit Project File). You can read this to know more.