我想在Razor视图中显示查询结果。
我可以通过控制器获得所需的输出,但是我需要帮助才能在视图中显示。
Fuel
类:
public class Fuel
{
public int FuelId { get; set; }
public int FMonth{ get; set; }
public int Year { get; set; }
}
Location
类:
public class Location
{
public int LocationId { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
现在,我使用视图模型类FuelLocation
加入两个表:
public class FuelLocation
{
public Fuel Fuels { get; set; }
public Location Locations { get; set; }
}
这是控制器中的操作方法:
public ActionResult EmpDetails()
{
var res = (from loc in _context.Locations
join Fl in _context.Fuels on loc.Name equals Fl.Locationn
select new FuelLocation
{
Fuels = Fl,
Locations = loc
}).GroupBy(c => c.Fuels.Locationn)
.Select(g => new
{
Location = g.Key,
Jan = g.Where(c => c.Fuels.FMonth == 1).Sum(c => c.Fuels.Sale),
Feb = g.Where(c => c.Fuels.FMonth == 2).Sum(c => c.Fuels.Sale),
March = g.Where(c => c.Fuels.FMonth == 3).Sum(c => c.Fuels.Sale)
}).ToList();
}
此查询的结果是:
我想这样显示
Name | Jan | Feb | Mar | Total
1 | 100 | 350 | 250 | 700
2 | 200 | 220 | 2150 | 2170
我的剃刀视图:
@model IList<COSAuthNew.Services.Generic.FuelLocation>
<h2>Index</h2>
<table class="table">
<tr>
<th>LocationName</th>
<th>Jan</th>
<th>Feb</th>
<th>March</th>
<th>Total</th>
</tr>
@foreach (var item in Model)
{
//Plz enter your solution
}
但是我没有得到想要的正确结果。
谢谢
答案 0 :(得分:1)
要显示项目值,只需在td标签中的值之前添加@
。然后,您可以使用@(val1 + val2..)
@model IList<COSAuthNew.Services.Generic.FuelLocation>
<h2>Index</h2>
<table class="table">
<tr>
<th>LocationName</th>
<th>Jan</th>
<th>Feb</th>
<th>March</th>
<th>Total</th>
</tr>
@foreach (var item in Model)
{
<td>@item.Location</td>
<td>@item.Jan</td>
<td>@item.Feb</td>
<td>@item.March</td>
<td>@(item.Jan + item.Feb + item.March)</td>
}
答案 1 :(得分:0)
对于Razor View
,您需要返回一个包含Location
和Jan
属性的视图模型。
定义如下视图模型:
public class FuelLocationVM
{
public string Location { get; set; }
public int Jan { get; set; }
public int Feb { get; set; }
public int March { get; set; }
}
返回虚拟机而不是异常类型
var res = (from loc in _context.Locations
join Fl in _context.Fuels on loc.Name equals Fl.Locationn
select new FuelLocation
{
Fuels = Fl,
Locations = loc
}).GroupBy(c => c.Fuels.Locationn)
.Select(g => new FuelLocationVM
{
Location = g.Key,
Jan = g.Where(c => c.Fuels.FMonth == 1).Sum(c => c.Fuels.Sale),
Feb = g.Where(c => c.Fuels.FMonth == 2).Sum(c => c.Fuels.Sale),
March = g.Where(c => c.Fuels.FMonth == 3).Sum(c => c.Fuels.Sale)
}).ToList();
剃刀视图中的参考VM
@model IList<COSAuthNew.Services.Generic.FuelLocationVM>
<h2>Index</h2>
<table class="table">
<tr>
<th>LocationName</th>
<th>Jan</th>
<th>Feb</th>
<th>March</th>
<th>Total</th>
</tr>
@foreach (var item in Model)
{
<td>@item.Location</td>
<td>@item.Jan</td>
<td>@item.Feb</td>
<td>@item.March</td>
<td>@(item.Jan + item.Feb + item.March)</td>
}