How to detect if form field has changed without us

2019-05-31 23:27发布

问题:

I am using ASP.NET MVC 3 and have a need to detect if the form field has been changed on the server side. I know about using tricks with hidden fields, but I was wondering if there is a way to do it by just using the API?

Basically, I have edit screen for my model and one of the fields is an optional id that can be specified. If the field is specified, I have to insure it is unique (no other model has it). So on the edit controller, I want to run the validation but only if that field has been changed.

Please note, I don't need to know previous value vs. new value, just if the field value has changed.

回答1:

You will have to keep a copy of the old value somewhere, and do the comparison. You may store it in your View Model.



回答2:

There is indeed no 'dirty' flag - MVC actually is closer to "the way the web works" to reuse that statement. All that is sent over are name value pairs. nothing else. MVC's model binder just matches those names to your object - so in order to truly detect a change you have to either validate against the true data source upon post or compare values passed in on the form - in which case - it is best to hash to avoid forgery.