2

我试图根据查询字符串中的值填充视图模型。这是我的控制器:

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);
}

所以它不会让我将视图模型返回到视图,说“视图模型在当前上下文中不存在”。它不会让我在 if 语句之外声明视图模型。这应该怎么做?

4

2 回答 2

1

尝试在视图结果中移出 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);

}
于 2012-06-12T02:53:45.897 回答
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);
}
于 2012-06-12T03:01:56.013 回答