0

我有以下代码:

    if (pick == null || pick == "active")
    {
       var Proj = db.usp_Train(idnbr)
                 .Where(a => a.Inactive == false).ToList();
     }        
     else 
     {
       var Proj = db.usp_Train(idnbr).ToList();

     }

return PartialView(Proj);

对于我返回 PartialView(Projs)的地方,我收到一条消息,说Proj 在当前不存在关于如何解决这个问题的任何想法。

4

5 回答 5

3
if (pick == null || pick == "active")
{
    return PartialView(db.usp_Train(idnbr).Where(a => a.Inactive == false).ToList());
}
return PartialView(db.usp_Trainin(idnbr).ToList());

或者,如果您愿意:

List<Project> projects;
if (pick == null || pick == "active")
{
    projects = db.usp_Train(idnbr).Where(a => a.Inactive == false).ToList();
}
else
{
    projects = db.usp_Trainin(idnbr).ToList();
}
return PartialView(projects);
于 2012-06-25T19:57:04.920 回答
3

您在and块Proj的范围内声明-因此它不存在于这些块之外。你想要这样的东西:ifelse

// Or whatever the type is...
List<Train> proj;

if (pick == null || pick == "active")
{
    proj = db.usp_Train(idnbr)
             .Where(a => a.Inactive == false).ToList();
}        
else 
{
    proj = db.usp_Train(idnbr).ToList();
}
return PartialView(proj);

或者,您可以使用条件运算符:

bool pickActive = pick == null || pick == "active";
var proj = pickActive ? db.usp_Train(idnbr).Where(a => !a.Inactive).ToList()
                      : db.usp_Train(idnbr).ToList();
return PartialView(proj);

或者有选择地应用条件,这会消除所有冗余:

IQueryable<Train> proj = db.usp_Train(idnbr);
if (pick == null || pick == "active")
{
    proj = proj.Where(a => !a.Inactive);
}
return PartialView(proj.ToList());
于 2012-06-25T19:57:32.790 回答
0

您定义Proj的范围太窄。

//define Proj here!
List<Train> Proj = null;

if (pick == null || pick == "active")
    {
       Proj = db.usp_Train(idnbr)
                 .Where(a => a.Inactive == false).ToList();
     }        
     else 
     {
       Proj = db.usp_Train(idnbr).ToList();

     }

return PartialView(Proj);
于 2012-06-25T19:57:17.760 回答
0

您需要确保您的Proj变量在任何被访问的地方都保持在范围内。由于var需要在声明变量的位置分配变量,我的建议是重构您的逻辑以避免重复声明:

var proj = db.usp_Train(idnbr);

if (pick == null || pick == "active")
    proj = proj.Where(a => a.Inactive == false);

return PartialView(proj.ToList());    
于 2012-06-25T19:57:32.987 回答
0

Proj 的范围有限。像这样声明它:

    (whatever type Proj is) Proj;

    if (pick == null || pick == "active") 
        { 
            Proj = db.usp_Train(idnbr) 
                     .Where(a => a.Inactive == false).ToList(); 
         }         
         else  
         { 
            Proj = db.usp_Trainin(idnbr).ToList(); 

         } 


return PartialView(Proj); 
于 2012-06-25T19:57:48.667 回答