dynamicuser
dynamicuser

Reputation: 1552

MVC prevent updating certain fields

I have an ASP.NET MVC 4 application using repository pattern and Entity Framework 6.

When I visit User/Details/5 page and update a users details, I get the following error -

The property 'Password' cannot be set to a null value.

In my view, I have all these fields apart from Password, as I have no need for it in this view. How can I (essentially) tell MVC to not update the password in this view?

This is my UserModel

public class UserModel : IUserModel
{
    public int Id{ get; set; }

    [DisplayName("Employee Number")]
    public int EmployeeNumber { get; set; }

    [DisplayName("First Name")]
    public string Firstname { get; set; }

    [DisplayName("Last Name")]
    public string Surname { get; set; }

    public string Email { get; set; }

    [DisplayName("User Type")]
    public UserType UserType { get; set; }

    [DisplayName("Login")]
    public UserStatus UserStatus { get; set; }

    [DisplayName("Login Status")]
    public bool LoginStatus { get; set; }

    public string Password { get; set; }

    [ReadOnly(true)]
    public DateTime DateCreated { get; set; }

    [ReadOnly(true)]
    public int CreatedBy { get; set; }

    [ReadOnly(true)]
    public DateTime LastUpdated { get; set; }

    [ReadOnly(true)]
    public int LastUpdateBy { get; set; }

    [DisplayName("Full Name")]
    public string SurnameFirstName
    {
        get { return Surname + ", " + Firstname; }
    }

    [NotMapped]
    public State State { get; set; }
}

and this is my controller -

[HttpPost]
    public ActionResult Details(UserModel model)
    {
        if (ModelState.IsValid)
        {

            _userService.Update(model);

            return RedirectToAction("Index");
        }

        return View(model);
    }

And my _userService.Update method

public void Update(UserModel entity)
    {
        User u = _userRepository.FindById(entity.Id);

        AutoMapper.Mapper.CreateMap<UserModel, User>();

        _userRepository.Update(AutoMapper.Mapper.Map(entity, u));
    }

Upvotes: 1

Views: 1261

Answers (1)

Peter Porfy
Peter Porfy

Reputation: 9040

Your key sentence is this:

In my view, I have all these fields apart from Password, as I have no need for it in this view.

You should define ViewModels instead of playing with the model (I know there is a lot of examples which do it like you, but the best practice is using viewmodels).

A ViewModel is basically a class which models your views so it only contains the properties you need. After you get this you can update your model as @krillgar said in a comment: pull the user from the database and update only the fields you want to update.

Upvotes: 4

Related Questions