My _Layout
uses the BaseViewModel to render the user's name in the navbar which i want to keep consistent through the application. My HomeController
has an action on it called Login that passes a UserViewModel
to the Dashboard
view upon successful login. UserViewModel
derives form BaseViewModel
and is only used in the Dashboard view right now.
My question is how do I make this BaseViewModel which will be used by the _Layout page be available throughout the views of the application. Do I have to keep making a call to my service (Database) to fetch this data each time a page loads? because the data that the BaseViewModel needs is only fetched in the Login
action of the HomeController
so the page breaks if i navigate to another view, and I get this error below
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[InventoryManager.Web.Models.ProductViewModel]', but this dictionary requires a model item of type 'InventoryManager.Web.Models.BaseViewModel'.
BaseViewModel.cs
public class BaseViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
UserViewModel
public class UserViewModel : BaseViewModel
{
public Guid UserId { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
BaseController
public class BaseController : Controller
{
//
// GET: /Base/
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
var model = filterContext.Controller.ViewData.Model as BaseViewModel;
}
}
HomeController
public ActionResult Login(LoginViewModel model)
{
if (!ModelState.IsValid)
{
return ReturnLoginViewOnError(CustomErrorMessages.LOGIN_CREDENTIALS_NOT_PROVIDED);
}
var userService = new UserServiceClient();
var user = userService.GetUser(model.Username, model.Password);
if (null == user)
{
return ReturnLoginViewOnError(CustomErrorMessages.INVALID_USER);
}
var userViewModel = Mapper.Map<UserContract, UserViewModel>(user);
return RedirectToAction("Index", "Dashboard", userViewModel);
}