Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check a change in a Model Object fields without checking individual fields in MVC?

I have a big model

public class SomeModel
{
        public int Id { get; set; }
        .....A lot(24) of Fields here.....
}

Now on Post ActionResult Edit(somemodel SomeModel) I want to check if anything has been changed by user with respect to original model values in database. Using If Else makes for a lot of messy code. Is there anyway to check if something was altered by the user and if possible what field was altered by user?

like image 429
Flood Gravemind Avatar asked Apr 01 '15 13:04

Flood Gravemind


People also ask

What is@ model in Cshtml?

This @model directive allows you to access the movie that the controller passed to the view by using a Model object that's strongly typed. For example, in the Details. cshtml template, the code passes each movie field to the DisplayNameFor and DisplayFor HTML Helpers with the strongly typed Model object.

How keep original value for some field when execute edit on MVC?

You can use TryUpdateModel() like so...... [HttpPost] public ActionResult Edit(int id, FormCollection collection) { using (var context = new DocInvoiceEntities()) { var client = context. Clients.

Which object is used to access the model data in controllers?

The ViewBag is a dynamic object that provides a convenient late-bound way to pass information to a view. MVC also provides the ability to pass strongly typed objects to a view template. This strongly typed approach enables better compile-time checking of your code and richer IntelliSense in the Visual Studio editor.


1 Answers

I was thinking about using a method like this one

    public class SomeModel
    {
    //... 
     public override bool Equals(object obj)
        {
      var type = this.GetType();
      bool SameObj = true;
     //for each public property from 'SomeModel'
     //[EDITED]type.GetProperties().Each(prop=>{ //  Sorry i'm using custom extension methode here
     //you should probably use this instead
     type.GetProperties().ToList().ForEach(prop=>{
                      //dynamically checks that they're equals 
                      if(!prop.GetValue(this,null).Equals(prop.GetValue(obj,null))){
                          SameObj=false;
                      }
                    }
                return SameObj;
    }
   }

/!\ Edited

like image 188
Emmanuel M. Avatar answered Sep 27 '22 16:09

Emmanuel M.