Translate

jueves, 27 de marzo de 2014

ASP:NET MVC More than one model in the same view

In this case I have two models that I need to pass to the view because I need data from both classes. The first one is associated to the class UserProfile which manages the userName, userID, email, and all the data for a given user:


The second model manages the passwords for the user name. These data are stored encrypted  into a different file in order to prevent access to see the password. Both classes have Data Annotations to describe label fields,keys, required data, etc. In this link you could find info about regular expressions to validate data entered in data fields.



In my example I need  to use data from both classes(models) when a new user is being registered, that is, enter username, password and all the other data, so I need to pass both models to the same view, in which data could be entered. This is the code for the view, using data from both models:


An this is how this view is showed in the browser:


MVC allows you to pass only one model to a View, but you can use different ways to pass more than one. The way I do it, is using an auxiliary class in which you can put all the models you want to pass to the view. So this is the additional class including the two classes mentioned above:


And this is the method associated with the view, saving data for both models:


No hay comentarios: