Im trying to populate a viewmodel based on the value from the querystring. Heres my controller:
public ViewResult Index(int? ShiftStatusID)
{
//Get logged in User
User user = _accountService.GetUser(_formsAuthService.GetLoggedInUserID());
if (ShiftStatusID == null) // Get all shifts
{
ViewModelShiftList viewModel = new ViewModelShiftList
{
Shifts = _shiftService.GetShifts(user.organisationID.Value).ToList()
};
}
else // Get shifts by status id
{
ViewModelShiftList viewModel = new ViewModelShiftList
{
Shifts = _shiftService.GetShiftsByStatus(user.organisationID.Value, ShiftStatusID).ToList()
};
}
return View(viewModel);
}
So it wont let me return the viewmodel to the view, saying “viewmodel does not exist in the current context”. It wont let me declare the view model outside the if statement. How should this be done?
Try to move out if statement in your viewresult.
Here is a code example which should be working fine: