使用TryUpdateModel使用FormCollection在Edit Post上保存对象 [英] Using TryUpdateModel to save an object on Edit Post with FormCollection

查看:60
本文介绍了使用TryUpdateModel使用FormCollection在Edit Post上保存对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定我是否了解执行此操作的最佳方法。

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

如果我有一个包含大量字段的模型,那么我是否必须在TryUpdateModel下的白名单中明确列出它们中的每一个,还是可以通过Forp。

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.

感谢您的帮助!

推荐答案

如果模型中的某些字段不在表单中,并且您不希望用户更改,则可以使用排除列表。使用包含列表或排除列表的选择取决于最大的列表。包含列表更安全,就好像您忘记包含无法更改的内容一样。不使用包含或排除列表将使您容易受到模型填充的困扰,在模型填充中,用户可以发布额外的值来更改他们不应该使用的详细信息。

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.

这篇关于使用TryUpdateModel使用FormCollection在Edit Post上保存对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆