简体   繁体   中英

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

<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

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

and sumbmit to:

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. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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