0

我有以下代码。

错误在这一行:if (testinstances == null)

当前上下文中不存在名称 testinstances。

是什么导致了这个错误?

public ActionResult Index(int? classRoomId, int? courseId, int? testTypeId)
{
    var classRoom = cls.GetAll();
    var course = cos.GetAll();
    var testType = tst.GetAll();

    ViewBag.ClassRoomID = new SelectList(classRoom, "ClassRoomID", "ClassRoomTitle");
    ViewBag.CourseID = new SelectList(course, "CourseID", "Title");
    ViewBag.TestTypeID = new SelectList(testType, "TestTypeID", "TestTypeDesc");


    if (classRoomId == null || courseId == null || testTypeId == null)
    {
        var testinstances = tt.GetAll();
    }
    else
    {

        var testinstances = tt.GetAll().Where(t => t.TestTypeID == testTypeId &&
                                              t.ClassRoomID == classRoomId &&
                                              t.CourseID == courseId);
    }

    if (testinstances == null)
    {
        throw new ArgumentNullException("No Test Found.Do you want to create one?");

        RedirectToAction("Create");

    } 
    return View(testinstances.ToList());  
}
4

1 回答 1

2

您只testinstancesif/else块内声明,但您试图在外部使用它。尝试在外部声明它,如下所示:

// Note, you must explicitly declare the data type if you use this method
IQueryable<SomeType> testinstances; 

if (classRoomId == null || courseId == null || testTypeId == null)
{
    testinstances = tt.GetAll();
}
else
{
    testinstances = tt.GetAll().Where(t => t.TestTypeID == testTypeId &&
                                      t.ClassRoomID == classRoomId &&
                                      t.CourseID == courseId);
}

if (testinstances == null)
{
    throw new ArgumentNullException("No Test Found.Do you want to create one?");
    RedirectToAction("Create");
} 
return View(testinstances.ToList());  

或者可能更清洁一点:

var testinstances = tt.GetAll();

if (classRoomId != null && courseId != null && testTypeId != null)
{
    testinstances = testinstances.Where(t => t.TestTypeID == testTypeId &&
                                        t.ClassRoomID == classRoomId &&
                                        t.CourseID == courseId);
}

if (testinstances == null)
{
    throw new ArgumentNullException("No Test Found.Do you want to create one?");
    RedirectToAction("Create");
} 
return View(testinstances.ToList());  
于 2013-10-15T01:17:11.160 回答