1

I'm not sure I understand the best way of doing this.

If I have a model with a large number of fields, then do I have to explicitelly list every one of them in a whitelist under TryUpdateModel, or can I just pass the ForCollection.

The following code doesn't save my edits, is my only alternative to list all my fields one by one?

public ActionResult Edit(int id, FormCollection form)
{            
    var jobToUpdate = db.Jobs
        .Include(x => x.JobNotes)
        .Where(x => x.JobID == id)
        .SingleOrDefault();

    if (TryUpdateModel(jobToUpdate, form))
    {

        db.Entry(jobToUpdate).State = EntityState.Modified;
        db.SaveChanges();

        return RedirectToAction("Details", new { id = model.Job.JobID });
    }
    return RedirectToAction("Details", new { id = model.Job.JobID })
}

Secondly, what is the best way to get a list of just the fields that have changed. If the only field that the user changes is the FirstName field, I'd like to record that in an audit log.

Thanks for your help!

Evonet
  • 3,600
  • 4
  • 37
  • 83

1 Answers1

1

If there are fields on your model that aren't in the form and you don't want users to change then you can use an exclude list. The choice to use an include or exclude list will depend which is largest. An include list is more secure as if you forget to include something it can't be changed. Not using an include, or exclude list will leave you vulnerable to model stuffing where users can post extra values to change details they shouldn't be able to.

public ActionResult Edit(int id, FormCollection form)
{            
    var jobToUpdate = db.Jobs
        .Include(x => x.JobNotes)
        .Where(x => x.JobID == id)
        .SingleOrDefault();

    if (TryUpdateModel(jobToUpdate, String.Empty, null, new [] {"SecretField"}, form))
    {
        db.SaveChanges();

        return RedirectToAction("Details", new { id = model.Job.JobID });
    }

    // Model not saved - send them back to edit page for corrections
    return View(jobToUpdate);
}

If the model is not saved you should not redirect. Show them the same page and make sure your edit view shows model errors.

The most likely reason your code is not saving the model is you're trying to insert a value that is not valid.

Richard Garside
  • 87,839
  • 11
  • 80
  • 93