简体   繁体   English

ASP.NET MVC:如何通过线路保持orignal对象状态

[英]ASP.NET MVC: How too keep orignal object state over the wire

Consider the following code: 请考虑以下代码:

public ActionResult Edit(int id)
{
    return View(db.Foos.Single(x => x.Id == id));
}

When user submits the changes, I would like to receive both original and current object values, such that the Update code can be: 当用户提交更改时,我希望同时接收原始和当前对象值,以便更新代码可以是:

Foo foo = db.Foos.Attach(current, original);
db.SubmitChanges();

I see two options: 我看到两个选择:

1) Render a number of hidden inputs containing original values 1)渲染包含原始值的多个隐藏输入

<input type="hidden" name="original.A" value="<%= Model.A %> />
<input type="hidden" name="original.B" value="<%= Model.B %> />

<input type="text" name="current.A" value="<%= Model.A %>
<input type="text" name="current.B" value="<%= Model.B %>

and submit to: 并提交至:

public ActionResult Update(Foo current, Foo original)
{
    Foo foo = db.Foos.Attach(current, original);
    db.SubmitChanges();
}

2) Use some serialization/deserialization into one hidden field 2)在一个隐藏字段中使用一些序列化/反序列化

<input type="hidden" name="original" value="<%= Serialize(original) %> />

and sumbmit to: 和sumbmit:

public ActionResult Update(Foo current, string original)
{
    Foo original = DeserializeFrom<Foo>(original);
    Foo foo = db.Foos.Attach(current, original);
    db.SubmitChanges();
}

Are there any other options? 还有其他选择吗? Or tools that make writing such code easier? 或者使编写此类代码的工具更容易?

EDIT: 编辑:

To be more clear... the idea of keeping original value is to eliminate extra select that happens if code written this way: 更清楚......保持原始价值的想法是消除如果以这种方式编写代码时发生的额外选择:

public ActionResult Update(Foo changed)
{
    Foo original = db.Foos.Single(x => x.Id == changed.Id);
    MyUtils.CopyProps(original, current);
    db.SubmitChanges();
}

make some custom HtmlHelper extension methods that simply write out both the hidden and textbox element. 制作一些自定义的HtmlHelper扩展方法,只需写出隐藏和文本框元素。 That way, your view markup stays simple, but you still get the pre/post state tracking in your post info. 这样,您的视图标记仍然很简单,但您仍然可以在帖子信息中获得前/后状态跟踪。

I would stray away from the serialization option :-/ 我会偏离序列化选项: - /

While I wouldn't know how to solve your problem, I can tell you that what you're thinking of would be extremely unsafe. 虽然我不知道如何解决你的问题,但我可以告诉你,你所想的将是非常不安全的。 In fact nothing would stop the client from altering the data sent through the request and in the best case have invalid data entered in your database. 实际上,没有什么能阻止客户端改变通过请求发送的数据,并且在最好的情况下,在数据库中输入了无效数据。 You should not trust the client with hidden fields, querystrings or cookies containing data you have to insert (unless you sign the data sent to the client in the first place and check the signature later). 您不应该信任包含隐藏字段,查询字符串或包含您必须插入数据的cookie的客户端(除非您首先签署发送给客户端的数据并稍后检查签名)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM