我有一个包含两个外页的View页面(@ {Html.RenderAction)在One中。 所有3页都有一个控制器。默认情况下,我从MSSQL数据库获取所有数据,我有结果。现在我需要按日期过滤结果,并在某些日期之间取得结果。
以下是HTML代码搜索表单:
@using (Html.BeginForm("Reporti", "Reporti", null, FormMethod.Get))
{
<table border="0" cellspacing="5" cellpadding="5">
<tbody>
<tr>
<td>Od Datum:</td>
<td><input type="text" id="datumOD" name="datumOD" class="datumOD"></td>
</tr>
<tr>
<td>Do Datum:</td>
<td><input type="text" id="max" name="datumDO" class="datumDO"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Baraj" /></td>
</tr>
</tbody>
</table>
}
网页网址为:h ** p:// localhost:41777 / Reporti / Reporti
点击搜索按钮后,我有这个网址
ħ**号码://本地主机:41777 / Reporti / Reporti datumOD = 2017年3月1日和安培; datumDO = 2017年3月2日
这是控制器的代码
public ActionResult Reporti(string filter, DateTime? datumOD, DateTime? datumDO)
{
Session["invoiceFrom"] = datumOD;
Session["invoiceTo"] = datumDO;
return View();
}
public ActionResult reportIZ(DateTime? datumOD, DateTime? datumDO)
{
var smetkis = db.smetkis.Include(s => s.firmi);
return View(smetkis.ToList());
}
public ActionResult Report(DateTime? datumOD, DateTime? datumDO)
{
var ponudis = db.ponudis.Include(s => s.ponudaDets).Where(x => x.odobreno);
return View(ponudis.ToList());
}
我的问题是,如何在公共ActionResult Reporti 中实现代码来过滤日期之间的结果。
答案 0 :(得分:0)
添加另一个条件:
public ActionResult Reporti(DateTime? datumOD, DateTime? datumDO)
{
var ponudis = db.ponudis.Include(s => s.ponudaDets).AsQueryable();
if(datumOD.HasValue) //If we have date - add condition
ponudis = ponudis.Where(x => x.odobreno >= datumOD);
if(datumDO.HasValue) //If we have date - add condition
ponudis = ponudis.Where(x => x.odobreno <= datumDO);
return View(ponudis.ToList());
}
如果您需要同时从2个表中获取数据,则应使用Union
。但是如果你的表有不同的结构,你应该创建单独的类,如RowViewModel
。像这样:
public class RowViewModel
{
public int Id {get; set;}
public int DateTime? Odobreno {get; set;}
//your other properties
}
然后在你的控制器中:
public ActionResult Reporti(DateTime? datumOD, DateTime? datumDO)
{
var ponudis = db.ponudis.Include(s => s.ponudaDets).AsQueryable();
var smetkis = db.smetkis.Include(s => s.firmi).AsQueryable();
if(datumOD.HasValue) //If we have date - add condition
{
smetkis = smetkis.Where(x => x.odobreno >= datumOD);
ponudis = ponudis.Where(x => x.odobreno >= datumOD);
}
if(datumDO.HasValue) //If we have date - add condition
{
smetkis = smetkis.Where(x => x.odobreno >= datumOD);
ponudis = ponudis.Where(x => x.odobreno <= datumDO);
}
var res = smetkis.Select(x => new RowViewModel
{
Id = x.ID,
Odobreno = x.odobreno
//other properties if you need
}).Union(ponudis.Select(x => new RowViewModel //note Union
{
Id = x.ID,
Odobreno = x.odobreno
//other properties if you need
}));
return View(res);
}