1

I just ran into a little error in my MVC application.

Administrators can edit user profiles. Including the roles in which the user is.

So I have a ViewModel for "EditUser":

public class EditUserViewModel
{
    public User User { get; set; }
    public IEnumerable<SelectListItem> PossibleRoles { get; set; }
    public int[] SelectedRoles { get; set; }
}

So, on my EditUser.cshtml page, I just run a @Html.EditorFor(Model => model.User) which generates the needed fields, according to the limitations of my MetaData class.

There, for example I have made annotations like this one:

    [ScaffoldColumn(false)]
    public string Password { get; set; }

The problem with this is, that when I post back my edit form, the values that are set as Scaffold false, are null. Which seems kind of logical because there is no edit box for those properties.

So when I save my entity it overwrites the values values with null. (E.g If I update a user's name, and save, the user's password is overwritten with null and EF throws an error) Is there any way I could update the values automatically (according to the ones that I was able to edit (MetaDataClasses)?) ? Otherwise, if I copy them over to a freshly fetched entity from the Entity Framework, and I should change an annotation to Scaffold(false), I need to add a rule to the code where I copy the new values into the entity. And that just seems wrong.

Thanks in advance.

Christophe De Troyer
  • 2,852
  • 3
  • 30
  • 47

2 Answers2

2

EF works with whole entity and if you decide to not show some part of the entity you must also somewhere handle this when saving changes. You have multiple options:

  • Don't use the entity if you don't want to show all its data. Use special view model instead containing only data you want to show. Use that view model to collect changes and copy them to the entity (you can for example use AutoMapper for transforming entity to view model and vice versa).
  • Load the entity from database and update only fields you want to persist from your edit view model
  • Don't set whole user entity as updated. Instead set manually every property you want to update.
Community
  • 1
  • 1
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • Wonderful! Thanks for the complete answer! :) I think I know where to look! Didn't know about AutoMapper and manual property states, so thanks a lot!! :) – Christophe De Troyer Aug 06 '12 at 23:14
0

You could also use a hidden input. Not sure if doing that for a password is a great idea though.

@Html.HiddenFor(model => model.Property)
Flexo
  • 87,323
  • 22
  • 191
  • 272
Scott
  • 1