Using TryUpdateModel to save an object on Edit Post with FormCollection

不羁岁月 提交于 2020-01-16 01:33:08

问题


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!


回答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.



来源:https://stackoverflow.com/questions/18657898/using-tryupdatemodel-to-save-an-object-on-edit-post-with-formcollection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!