我有以下代码。
错误在此行: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());
}
答案 0 :(得分:2)
您只在testinstances
/ if
块中声明了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());