Justin
Justin

Reputation: 137

MVC ASP - Stopping edit function from modifying fields to NULL

So I'm trying to update ONLY specific data in my MVC application. Whenever I only edit a list view, I would edit the data (which works) but the rest of the database table would be NULL.

So for example -

Fields in List View

EmployeeID, FirsName, LastName, Email, Moderator, Admin

Fields not in list view

LoginID


So in my edit page, I have set up read-only for the info like EmployeeID, FirstName, LastName, and Email with two checkboxes for Moderator and Admin which are the only values I want to edit.

They work fine but when doing so, the data in the database for LoginID only becomes NULL.

Here is the code from my edit GET and POST methods

GET

public ActionResult Edit(int id)
{
    EmpContext ec = new AppContext();
    Employee e = ec.Employees.Single(x => x.Id == id);
    return View();
}

POST

public ActionResult Edit(Employee employee)
{
    if (ModelState.IsValid)
    {
        EmpContext ec = new EmpContext();
        ec.Entry(employee).State = EntityState.Modified;
        ec.SaveChanges();
        return RedirectToAction("List");
    }
            
    return View(employee);
}

So, how would I stop this executing in the field LoginID within the database when there are no text boxes at all for LoginID, even on the edit page?

Upvotes: 0

Views: 315

Answers (1)

Yong Shun
Yong Shun

Reputation: 51125

According to Attaching an existing but modified entity to the context

When you change the state to Modified all the properties of the entity will be marked as modified and all the property values will be sent to the database when SaveChanges is called.

Thus, this Entry method will update all the properties. For my recommendation, to update some Entity's columns only, you have to manually query the record and update desired properties only.

In your Edit (POST) method, change the Entry() way to:

EmpContext ec = new EmpContext();
Employee _employee = ec.Employees.Single(x => x.Id == employee.Id);

// TO-DO Update required properties only
_employee.FirstName = employee.FirstName;
ec.SaveChanges();

Upvotes: 2

Related Questions