How to pass parameters to the ViewModel in MVC

On a user account page, I had to display specific information regarding the logged in user. Things like Name, Age etc. I designed a ViewModel called UserAccount which takes in a UserId as a parameter to its contructor and based on that value, the VM pulls information from the database for that specific user. Something like this:


public class UserAccount

{

public string Name { get; set;}

public int Age { get; set; }

public UserAccount(int userId)

{

User user = GetUserFromRepository(userId);

Name = user.Name;

Age = user.Age;

}

}

All information I needed was provided by the VM but when it came to attaching this VM to the View, I got stuck. I need to mention I’m quite new to MVC but then I managed to find the solution to this:


public ActionResult MyAccount()
 {
 if (!Helper.IsUserLoggedIn())
 {
 return Redirect(Helper.GetLoginPageWithRedirect());
 }
 else
 {
 var vm = new Core.ViewModel.UserAccount(Helper.GetUserIdFromSession());

return View(vm);
 }
 }

What this does is first check whether the user is actually logged in. If not, it redirects the user to the login page because they should not ┬ábe able to access the account page without being signed in. Since you can actually pass in an object when returning a View, you can already initialise your object through constructor injection and then do “return View(YourAlreadyInitialisedObject”);” That saved me from writing extra lines of codes and it works brillantly.

comments powered by Disqus