Razor edit form - is there an attribute or other convenient way to only bind a property if the value has changed?

StackOverflow https://stackoverflow.com/questions/21950120

Вопрос

One of my objects has a string ImportantName which must be unique and is often used in URL routing, a la http://www.mywebsite.com/objects/{ImportantName}.

I can allow (and need to allow) changes to ImportantName but when I do so I need to perform extra serverside validation and also redirect to a different URL in the case of a name change.

Of course I could add some jQuery to detect a change in value, or compare the old/new name on the server, but there has to be a better way, right?

Either of the following would work for me:

  1. Only send the ImportantName if it has changed from the initial value based on the provided model binding
  2. Add a boolean field to detect if ImportantName has changed and only send the value to the service if it has.

Right now I am working around this by adding both OldImportantName and NewImportantName to my FormModel and comparing on the server after post.

Это было полезно?

Решение

  • Only send the ImportantName if it has changed from the initial value based on the provided model binding
  • Add a boolean field to detect if ImportantName has changed and only send the value to the service if it has.

If you want to implement either of the above mentioned options, you can only accomplish them on the client side using JQuery. I am saying so because, FORM has already been rendered on the client browser and including/excluding any properties from POST operation should be managed on the client side by making changes to the DOM (if you do not want to use AJAX, but if you decide to use AJAX, then you can only POST properties of you interest from client side using JQuery). In fact observing any changes to the model properties also needs to be done on the client side using JQuery.

So in this case, I would prefer to solve this requirement, exactly how you are solving it now but with little change. I do not include OLD/NEW values to the formModel, rather I will have only one property OLD, and I will identify change to it using JQuery OnChange. Then take necessary action. If you do not want to go for JQuery, then on FORM POST, you can use a ActionFilter on server side to check the changes in model (you have write some code to check changes in model, AFAIK there is no default mechanism in HTTP world to identify property changes) and make necessary server redirects.

Alternatively you can use JavaScript frameworks like KnockoutJS or AngularJs and they got Observable Arrays or collections, which can use to detect property changes on the client side with very little effort. And there by take necessary actions and POST only required and interested parameters through these frameworks.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top