Capturing old model values โ€‹โ€‹in MVC3?

I want to capture the old values โ€‹โ€‹in the model so that I can compare with the new values โ€‹โ€‹after submitting and create audit logs of the changes the user makes.

My guess is doing this with hidden input fields with duplicated old property values โ€‹โ€‹would be one way. But I wonder if there are other good alternatives?

thank

+5
source share
4 answers

In the save method, just go and get the source object from the database before , saving the changes, then you have your old and new values โ€‹โ€‹to compare with? :)

+9
source

. , , . - , .

:

CQRS, . , .

. . , .

, .

.

+2

, mattytommo,

public ActionResult Edit(int id) {
    var entity = new Entity(id); // have a constructor in your entity that will populate itself and return the instance of what is in the db
    // map entity to ViewModel using whatever means you use
    var model = new YourViewModel();
    return View(model);
}

[HttpPost]
public ActionResult Edit(YourViewModel model) {
    if (ModelState.IsValid) {
        var entity = new YourEntity(model.ID); // re-get from db
       // make your comparison here
       if(model.LastUserID != entity.LastUserID // do whatever
       ... etc...
    }
    return View(model);
}
+1

- ...

// In the controller
public ActionResult DoStuff()
{
    // get your model
    ViewBag.OriginalModel = YourModel;
    return View(YourModel);
}

// In the View
<input type="hidden" name="originalModel" value="@Html.Raw(Json.Encode(ViewBag.OriginalModel));" />

// In the controller post...
[HttpPost]
public ActionResult DoStuff(YourModel yourModel, string originalModel)
{
    // yourModel will be the posted data.
    JavaScriptSerializer JSS = new JavaScriptSerializer();
    YourModel origModel = JSS.Deserialize<YourModel>(originalModel);
}

I did not have the opportunity to verify this, just a theory :)

+1
source

All Articles