我试图根据查询字符串中的值填充视图模型。继承人我的控制人员:
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);
}
所以它不会让我将viewmodel返回到视图,说“viewmodel在当前上下文中不存在”。它不会让我在if语句之外声明视图模型。该怎么做?
答案 0 :(得分:1)
尝试在viewresult中删除if语句。 这是一个应该正常工作的代码示例:
public ViewResult Index(int? ShiftStatusID)
{
//Get logged in User
User user = _accountService.GetUser(_formsAuthService.GetLoggedInUserID());
var viewModel = new ViewModelShiftList();
if (ShiftStatusID.HasValue)// Get shifts by status id
{
viewModel.Shifts = _shiftService.GetShifts(user.organisationID.Value).ToList();
}
else // Get all shifts
{
viewModel.Shifts = _shiftService.GetShiftsByStatus(user.organisationID.Value, ShiftStatusID).ToList();
}
return View(viewModel);
}
答案 1 :(得分:0)
清理代码,删除重复的行:
public ViewResult Index(int? ShiftStatusID)
{
//Get logged in User
User user = _accountService.GetUser(_formsAuthService.GetLoggedInUserID());
List<Shift> shifts;
if(ShiftStatusID == null)
shifts = _shiftService.GetShifts(user.organisationID.Value).ToList();
else
shifts = _shiftService.GetShiftsByStatus(user.organisationID.Value, ShiftStatusID).ToList();
var viewModel = new ViewModelShiftList
{
Shifts = shifts
};
return View(viewModel);
}