Zholen
Zholen

Reputation: 1790

MVC best practice for view validation?

What is considered best practice for the following example:

Are these 3 separate views? Or the same view with multiple route options?

ActionResult ChangePassword()
ActionResult ChangePassword(string token)
{
// if bad token show this error view partial? set viewdata item and let cshtml decide what to show?
}

Or is a situation like this not really all that logical?

Upvotes: 1

Views: 159

Answers (3)

Jesse Webb
Jesse Webb

Reputation: 45303

I would separate it into 2 pages:

Change Password

  • users always enters old password and new one, new one twice for confirmation
  • no need to get username because they should be authenticated already
  • do not allow URL parameters to pre-populate values
  • use a CSRF token

Reset Password

  • only linked to from email with valid unique param
  • user only enters new password, twice for confirmation
  • no need to get username, URL param set by email already identifies user
  • do not use URL params to send anything else, e.g. temp passwords or usernames
  • no need to use CSRF token, other unique param already blocks against forgery

These two pages seem to operate differently enough that I think you would be better off using separate views, actions, & view models. If you get to the end though, there is nothing wrong with refactoring to remove duplication, but I would predict they will not be as similar as you anticipate.

Upvotes: 3

Mister Epic
Mister Epic

Reputation: 16743

I think you could get away with a single View, you just need to build a robust enough ViewModel:

 public class ChangePasswordViewModel(){
     public string OldPasswordHash {get; set;} //Remember never to store password in clear text
     public string NewPassword{ get; set; }
     public string RecoveryToken { get; set; }
 }

Based on these properties, you should have all you need to flesh out the presentation logic in your View to cover off all the use cases you describe above. Let me know if you need further guidance.

Upvotes: 2

Orel Eraki
Orel Eraki

Reputation: 12196

I think the best validation for ASP.NET MVC will be Validation Attributes on the properties you will like to validate.

Upvotes: 1

Related Questions