大家好,我正在玩 ASP.NET MVC 和 Entity Framework。我想知道处理数据从 Controller 传递到 View 然后返回的最佳方法是什么。我会解释得更好一点:
我有一个用于创建新“收据”对象的操作
[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 信息),然后我可以将其发送到一个包含各种表单元素的 View ,让用户填写其他缺失的内容字段并提交,以便添加新收据。如果收据对象中的所有字段都显示在表单上,这一切都很好。
如果我删除了用户不应该触摸的东西的表单元素(例如组号,收据所属的用户ID等......)那么当我提交表单并拿起它时在 Controller 中:
[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);
}
然后,我填写并发送到 View 的所有方便的预加载信息都不会随帖子一起返回。我知道我可以将 UserID 或 GroupID 放入一个隐藏字段,然后通过 POST 返回,但感觉不对。从技术上讲,有人可以进去,更改隐藏值并重新提交帖子。然后我可以进行检查以确保所有内容都应该在其所属的位置,但这也感觉像是又一次访问数据库以获取我曾经获得过的信息。
如果有人能详细说明将数据从模型传递到 View 再到 Controller 的标准方式,那就太好了。感谢您的宝贵时间和帮助!
最佳答案
如果您担心有人使用隐藏字段值来影响其他记录,请填充 ID 值并在隐藏字段中对其进行加密,然后在回发时解密。
关于c# - ASP.NET MVC 传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4208882/