hackp0int
hackp0int

Reputation: 4161

How to check if Form data have been modified?

I have a pretty complicated form and I don't want to make all the database queries, just because someone entered the update page.

How I would know if the content inside the form has been modified?

I don't use knockout.js and don't want to implement it.

Upvotes: 1

Views: 2296

Answers (2)

ePezhman
ePezhman

Reputation: 4010

maybe with some jQuery. assign some classes to field and fire the change event and put the name of the changed field in some hidden field, then you can have the field which have changed on server side.

<input type="hidden" id="changedNames" name ="changedNames" />


$(function () {
    $('.observe').change(function (e) {
        var thisName = $(this).attr('name');
        $('#changedNames').val($('#changedNames').val() + thisName + " ");

    });
});

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038820

You could use javascript. For example once the form is rendered you could calculate a checksum and before submitting it recalculate this checksum and compare the 2 values. Then you could set the value of a hidden field so that when the form is submitted to the server you would know whether something was modified:

String.prototype.hashCode = function() {
    var hash = 0;
    if (this.length == 0) return hash;
    for (i = 0; i < this.length; i++) {
        char = this.charCodeAt(i);
        hash = ((hash<<5) - hash) + char;
        hash = hash & hash;
    }
    return hash;
};

$(function() {
    var $form = $('form');
    $form.data('checksum', $form.serialize().hashCode())
    $form.submit(function() {
        var initialChecksum = $(this).data('checksum');
        var currentChecksum = $(this).serialize();
        var isDirty = initialChecksum != currentChecksum;
        $('#isDirty').val(isDirty);
    });
});

and your view model could have an IsDirty boolean property that you could query in the controller action that is processing the form submission.

Upvotes: 2

Related Questions