【发布时间】:2010-11-18 04:57:37
【问题描述】:
大家好,我正在使用 ASP.NET MVC 和实体框架。我想知道将数据从控制器传递到视图然后返回的最佳方法是什么。我会解释得更好一点:
我有一个用于创建新“收据”对象的操作
[Authorize]
public ActionResult CreateReceipt(int id)
{
//I create the receipt object
Receipt newReceipt = new Receipt();
// assign some information about the owner of the receipt
// and the group that it belongs to
newReceipt.Group = group;
newReceipt.Owner = user;
//send off to the view to be displayed
return View(newReceipt);
}
所以我基本上创建一个收据并预先填写一些信息(包括授权用户和一些组 ID 信息),然后我可以将其发送到一个包含各种表单元素的视图,让用户填写其他缺失的字段并提交,以便添加新收据。如果收据对象的所有字段都显示在表单上,这一切都很好。
如果我删除了用户不应该触摸的表单元素(例如组号、收据所属的用户 ID 等),那么当我提交表单并拿起它时在控制器中:
[HttpPost]
[Authorize]
public ActionResult CreateReceipt(Receipt receipt)
{
if (ModelState.IsValid)
{
using (EntityFrameworkEntities context = new EntityFrameworkEntities)
{
context.AddToReceipts(receipt);
context.SaveChanges();
}
return RedirectToAction("Index");
}
return View(receipt);
}
然后,我填写并发送到视图的所有方便的预加载信息都不会随帖子返回。我知道我可以将 UserID 或 GroupID 放入隐藏字段,然后通过 POST 将其返回,但这感觉不对。从技术上讲,有人可以进去,更改隐藏的值并重新提交帖子。然后我可以进行检查以确保所有内容都应该在它所属的位置,但这也感觉像是再次访问数据库以获取我曾经获得过的信息。
如果有人能详细说明将数据从模型传递到视图再到控制器的标准方式,那就太好了。感谢您的时间和帮助!
【问题讨论】:
标签: c# asp.net-mvc entity-framework-4