1

So, I have a problem I am curious about. I have a UserAccountViewModel that I am reusing for create account view and Edit Account view. So that I can use one view and one viewmodel for my code but different controller actions.

On Create Account, UserName, Password and Confirm Password are all required fields. However, on Edit Account, those fields are not required fields (I hide those fields in my view on Edit Account).

The problem is when I do this:

[HttpPost]
public ActionResult EditUserAccount_Save(UserAccountViewModel editUserAccountViewModel)
{
    var errors = ModelState.Values.SelectMany(v => v.Errors);
    if (ModelState.IsValid)
    {
        editUserAccountViewModel.UserName = UserSession.GetValue(StateNameEnum.UserName, StateNameEnum.UserName.ToString()) as string;

        db_user user = new db_user();
        user.Title = editUserAccountViewModel.Title;
        user.FirstName = editUserAccountViewModel.FirstName;
        user.LastName = editUserAccountViewModel.LastName;
        user.PhoneNumber = editUserAccountViewModel.PhoneNumber;
        user.AltPhoneNumber = editUserAccountViewModel.AltPhoneNumber;
        user.EmailAddress = editUserAccountViewModel.EmailAddress;
        user.LanguageId = context.languages.Where(t => t.Code == editUserAccountViewModel.Language).Select(t => t.Id).FirstOrDefault();
        user.CreatedDate = DateTime.Now;
        user.UserId = WebSecurity.GetUserId(editUserAccountViewModel.UserName);

        context.Entry(user).State = EntityState.Modified;
        context.SaveChanges();

        JsonResult res = Json(new { Success = true, data = "", Message = "" });
        return res;
    }
    JsonResult res2 = Json(new { Success = false, data = "", Message = "" });
    return res2; 
}

My ModelState.IsValid returns false and I added the errors statement above and it says:

It's because UserName, Password and Confirm Password fields are required. How can I reuse my viewmodel so that I can those fields required when I'm creating an account but not required on editing an account? That is, I want to keep those fields are the same (not editable in edit account?)

Daniel
  • 9,491
  • 12
  • 50
  • 66
Kala J
  • 2,040
  • 4
  • 45
  • 85
  • The whole point of using a view model is to include only those properties you need in the view - refer [What is ViewModel in MVC?](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc). Create 2 view models, `EditAccountVM` and `CreateAccountVM` (which inherits from `EditAccountVM` and includes the 3 additional required properties. –  Jul 20 '15 at 23:10

1 Answers1

4

You could output some dummy values into hidden fields in the view so they won't be null when they come back in, however, that is more data being pushed back and forth.

Secondly, you can remove the keys from the modelstate and thus remove their errors.

ModelState.Remove("UserName");
ModelState.Remove("Password");
ModelState.Remove("ConfirmPassword");

After doing that, when you call ModelState.IsValid, it will give the answer based only on the fields you are interested in

HTH

Slicksim
  • 7,054
  • 28
  • 32
  • ah okay, so I can do that in my controller before I check the model state? Thanks, it looks like something I can do. – Kala J Jul 20 '15 at 15:56
  • Oh I have a problem. On context.SaveChanges(), I get this exception: {"Validation failed for one or more entities. See 'EntityValidationErrors' property for more details."}. I get "DbEntityValidationException was unhandled by user code" – Kala J Jul 20 '15 at 15:59
  • You'll need to start a new question for that. If you look in the exception details and find the db validation errors, it might point you to what is wrong – Slicksim Jul 20 '15 at 16:17
  • How do I find or get the specific db validation errors? – Kala J Jul 20 '15 at 16:20
  • If you catch the exception in a try catch block, then set a breakpoint in the catch block. You will get the exception details there, you can dig through the object to find the validation errors – Slicksim Jul 20 '15 at 16:30
  • Now I am getting this issue (all in the same action): {"Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries."} – Kala J Jul 20 '15 at 16:35
  • I can't say I have seen that error before, have you googled it to see what causes it? – Slicksim Jul 20 '15 at 16:54
  • Yes, something about id being 0.Do I need to create a hidden field for my id? I think it might not know where to put the saved data? – Kala J Jul 20 '15 at 16:56
  • Looking at your code, what you want to do is fetch the user you are editing back from the db, update it's values with your view model, than ask the context to save it. To do that, you will need to know the id, so put out a hidden field with the id in it and then you can look up the user using that – Slicksim Jul 20 '15 at 16:58