1

The way I am doing this at the moment (which works) feels a bit hacky. When I am editing an entity I don't want the user to change key auditing fields behind, for example when the entity is initially created it automatically populates DateAdded, AddedBy, EditedBy.

To stop people editing these values I don't bind them in the include when editing:

public ActionResult Edit([Bind(Include = "Id,AccountName")] Account account)

This means I have to do this to get the original values back otherwise they get set to null

account.DateAdded = db.Accounts.Where(c => c.Id == account.Id).Select(d => d.DateAdded).FirstOrDefault();
account.AddedBy = db.Accounts.Where(c => c.Id == account.Id).Select(a => a.AddedBy).FirstOrDefault();
account.EditedBy = User.Identity.Name;

Is there a better way to fix this, the way below works but doesn't feel efficient.

Trinitrotoluene
  • 1,388
  • 5
  • 20
  • 39
  • 4
    Use a view model containing only the properties your need. In the POST method, get the data model from the database, map your view model properties to it and save the data model - refer [What is ViewModel in MVC?](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) –  Aug 17 '15 at 22:33
  • I agree with Stephen, is a good practice have entities which use Entity Framework and other classes (viewmodel, dto) that you use in the view or in a service. One excelent tool that can help you to map between entity and viewmodel and viceversa is automapper: http://automapper.org/ – Julito Avellaneda Aug 17 '15 at 23:27
  • Thanks Stephen, it does seem so obvious now! If you convert to an answer I'll mark it as complete. Thanks again. – Trinitrotoluene Aug 18 '15 at 00:12
  • Another option is to add those properties to your view model and pass them as hidden fields in your view. – tcrite Aug 18 '15 at 04:01

1 Answers1

0

The recommend approach is to use a view model containing only the proeprties you need to display/edit say

public class AccountVM
{
  public int ID { get; set; }
  public string Name { get; set; }
}

which then then use in the view and post back to your controller, get the data model based on the ID property and map the view model properties to you data model and save. Note the [Bind] attribute is not required.

Using view models has numerous advantages including application of view specific attributes and prevention of overposting attacks. For more information refer the answers to What is ViewModel in MVC?

Tools such as automapper make it easier to map ata between you data and view models.

Community
  • 1
  • 1