ASP.NET MCV. How to use TryUpdateMode method instead of Bind attributes to avoid Concurrency conflicts and overposting
If you use EF (Entity Framework) in your MVC pattern and you are writing new controller to edit data then you usually generate code by scaffolder generator to save time. But generated Edit action method is not recommended anymore in enterprise or business applications because of lack data protection. The generated code has this problem:
Generated by scaffolder action method takes entity field values via input parameters which can be easily provided via HTTP POST by hackers. It means that you need more invest in adding an additional technology to handle protection from possible many generated HTTP post requests by such including the ValidateAntiForgeryToken attribute which helps prevent cross-site request forgery attacks;
Recommended by Microsoft solution:
After generating by scaffolder or when you do it from scratch it is recommended to start use Controller.TryUpdateModel Method. The new code reads the existing entity and calls TryUpdateModel to update fields from user input in the posted form data.
Look at two screenshots below with bad code and with enhanced code, One important notice is here: As a result of these changes, the method signature of the HttpPost Edit method is the same as the HttpGet edit method; therefore you've renamed the method EditPost.
Picture 1: Generated by scaffolder Edit method which requires additional investments in future to protect information.
Picture 2: Recommended manually modified Edit method to updated data when source of data is Input Form of your view.