2013-10-15 41 views
0

我有以下代碼。名稱'testinstances'在當前上下文中不存在

的錯誤是在這一行: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()); 
} 

回答

1

你只是聲明瞭if/else塊內testinstances,但是你想在室外使用。嘗試宣告它外面的,就像這樣:

// 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()); 
+0

感謝P.S.W.g你的答案。與您的答案,我宣佈testinstances和它的作品。你是A + –

+0

@frank請務必接受他的回答。 – dcaswell

相關問題