我正在尝试将RenderAction中的null值传递给另一个视图。但是在两者之间,在控制器中,我的linq lambda表达式没有加载正确的字段,尽管空值正确通过..
SprintManager.cshtml
<div id="Global_Backlog_Board" class="Board_Panel">
@{Html.RenderAction("ListOfSingleCards", new
{
State_ID = 1
});}
</div>
HomeController.cs
public PartialViewResult ListOfSingleCards( int? Sprint_ID,
int State_ID = 1)
{
var Cards = db.Cards.Where(x => x.State_ID == State_ID &&
x.Sprint_ID == Sprint_ID &&
x.Deleted != 1 &&
x.Archive != 1).ToList();
return PartialView(Cards);
}
所以Sprint_ID在这里被传递并加载为null,但我无法让查询正确加载行。
事实上,以下工作:
var Cards = db.Cards.Where(x => x.State_ID == State_ID &&
x.Sprint_ID == null &&
x.Deleted != 1 &&
x.Archive != 1).ToList();
所以我想我可以检查Sprint_ID是否为空,并根据结果运行两个单独的查询中的一个,但我想了解为什么我的原始尝试不起作用。
谢谢!
答案 0 :(得分:1)
一个可空的int不会以你想的方式返回“null”。你必须检查它的HasValue属性以确定是否有值,如果有,那么使用它,否则使用null:
public PartialViewResult ListOfSingleCards( int? Sprint_ID,
int State_ID = 1)
{
var Cards = db.Cards.Where(x => x.State_ID == State_ID &&
x.Sprint_ID == Sprint_ID.HasValue ? Sprint_ID.Value : null &&
x.Deleted != 1 &&
x.Archive != 1).ToList();
return PartialView(Cards);
}
答案 1 :(得分:1)
我不知道正确的答案,但根据您的解决方案,您应该能够整理它:
var cards = new List<Card>();
var query = db.Cards.Where(x => x.State_ID == State_ID &&
x.Deleted != 1 &&
x.Archive != 1);
if (Sprint_ID.HasValue)
query = query.Where(x => x.Sprint_ID == Sprint_ID);
else
query = query.Where(x => x.Sprint_ID == null);
cards = query.ToList();
答案 2 :(得分:0)
直到更好的事情发生,我正在使用它:
var Cards = new List<Card>();
if (Sprint_ID == null)
{
Cards = db.Cards.Where(x => x.State_ID == State_ID &&
x.Sprint_ID == null &&
x.Deleted != 1 &&
x.Archive != 1).ToList();
}
else
{
Cards = db.Cards.Where(x => x.State_ID == State_ID &&
x.Sprint_ID == Sprint_ID &&
x.Deleted != 1 &&
x.Archive != 1).ToList();
}