编辑时的 ASP.NET MVC3 模型绑定
在过去的几年里,我正在开发第 5 个左右的 ASP.NET MVC Web 应用程序,但我仍然没有找到一种好的方法来获取编辑/更新表单中提交的数据,并在使用时有效地将其保存到数据库中像 Linq to SQL 或实体框架这样的 ORM。
需要明确的是,问题在于 Create 操作可以将对象作为参数:
public ActionResult Create(QuestionGroup newGroup)
使用 Edit 操作时,对象必须链接到 ORM 并更新,而不是像 ModelBinder 那样从头开始创建。
我总是通过以下两种方法之一解决这个问题:要么手动更新对象上的每个属性(每个属性一行代码),要么编写一个方法,使用反射来查找每个属性以更新它并将值复制到。
我确定认为,到目前为止,在 MVC 版本 3 中,有一种幸运的方法可以更好地做到这一点,但我找不到它!更简单、更优雅地做到这一点的秘诀是什么?
I'm working on my 5th or so ASP.NET MVC webapp in the past few years, and I still haven't seen a good way to take the data submitted in an Edit/Update form and save it to the database efficiently when using an ORM like Linq to SQL or the Entity Framework.
Just to be clear, the problem is with the Create action you can take the object as a parameter:
public ActionResult Create(QuestionGroup newGroup)
With an Edit action, the object must be linked to the ORM and updated, rather than created from scratch like the ModelBinder will do.
I have always solved this problem one of two ways: either I will manually update each property on the object (one line of code per property) or I will write a method that uses reflection to find every property to update it and copies the value over.
I feel certain that, by now in version 3 of MVC, there is a blessed way to do this better, but I cannot find it! What's the secret to do this more simply and gracefully??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
嗯,这很尴尬......有一个带有多个重载的方法 Controller.UpdateModel 可以解决这个问题。我在网上到处搜索,结果在发布问题后意外地用 IntelliSense 找到了答案。
Well this is embarrassing... there is a method Controller.UpdateModel with several overloads that will do the trick. I searched the internet hi and low, only to accidentally find the answer with IntelliSense right after posting the question.
我发现您还可以使用实体框架执行以下操作。与其他选项相比,它有优点和缺点,但它应该和前面的答案一样有效:
I've discovered that you can also do the following with the Entity Framework. It has pros and cons vs the other option, but it should work just as well as the previous answer: