我构建了以下格式的链接:http://localhost:33333/Invoices/Reports?format=pdf
当我运行时,它显示了这个错误:
System.InvalidOperationException:传递到字典中的模型项的类型为'System.Data.Entity.Infrastructure.DbQuery1[<>f__AnonymousType911[Webb.Models.Faktury,System.Int32,System.String,System.Nullable1[System.Single]]]', but this dictionary requires a model item of type 'System.Collections.Generic.List1Webb.Models.Faktury'. System.Nullable1[System.Single],System.Nullable1System.Int32,System.String,System.Nullable1[System.Single],System.Nullable1System.Single
查看:
@model List<Webb.Models.Faktury>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h2>Html Report</h2>
<p>
Lorem ipsum dolor sit amet</p>
<table width="100%">
<tr>
<td>User Name</td>
<td>Description</td>
<td>Lucky Number</td>
</tr>
@foreach (var item in Model)
{
<tr>
<td>@item.FAK_Id</td>
<td>................</td>
<td>@item.FAK_Numer</td>
</tr>
}
</table>
</body>
</html>控制器:
// Setup sample model
var pro = (from a in db.Fakturies
join b in db.Wierszes on a.FAK_Id equals b.WIE_Fkid
join c in db.Produkties on b.WIE_Pid equals c.PRO_Id
select new
{
a,
a.FAK_Id,
a.FAK_Numer,
a.FAK_DataS,
a.FAK_TerminZ,
a.FAK_Rabat,
b.WIE_Ilosc,
c.PRO_Nazwa,
c.PRO_CenaN,
c.PRO_CenaB,
c.PRO_Vat
});
pro = pro.Where(a => a.FAK_Id == 6);
// Output to Pdf?
if (Request.QueryString["format"] == "pdf")
return new PdfResult(pro, "Reports");
return View(pro);
}我应该怎么做才能用数据库中的数据将成功视图导出到pdf?
--编辑1:
public ActionResult Reports(int? id)
{
// Setup sample model
var pro = (from a in db.Fakturies
join b in db.Wierszes on a.FAK_Id equals b.WIE_Fkid
join c in db.Produkties on b.WIE_Pid equals c.PRO_Id
select a);
pro = pro.Where(a => a.FAK_Id == id);
var vm = new PrintViewModel();
vm.Fakturies = pro; //assuming pro is already loaded with the above code.
vm.Wierszes = db.Wierszes;
if (Request.QueryString["format"] == "pdf")
return new PdfResult(vm, "Reports");
return View(vm);
}发布于 2016-07-07 04:17:15
您的视图是强类型的Faktury集合。但是从您的action方法中,您正在传递一个匿名对象的集合。
更改您的LINQ表达式代码以使用Faktury类进行投影。
var pro = (from a in db.Fakturies
join b in db.Wierszes on a.FAK_Id equals b.WIE_Fkid
join c in db.Produkties on b.WIE_Pid equals c.PRO_Id
select a);
pro = pro.Where(a => a.FAK_Id == 6);
if (Request.QueryString["format"] == "pdf")
return new PdfResult(pro.ToList(), "Reports");
return View(pro);如果您需要传递比Fakturties列表更多的信息,您可以创建一个具有所需属性的视图模型。
public class PrintViewModel
{
public IEnumerable<Faktury> Fakturies {set;get;}
public IEnumerable<Wiersz> Wierszes {set;get;}
public PrintViewModel()
{
this.Fakturies = new List<Faktury>();
this.Wierszes = new List<Wiersz>();
}
}在您的action方法中,创建一个此对象,分配属性值并发送到视图。
var vm=new PrintViewModel();
vm.Fakturies=pro; //assuming pro is already loaded with the above code.
vm.Wierszes =db.Wierszes;
return View(vm);现在确保您的视图被强类型化为这个新的视图模型
@model PrintViewModel
<h3>Fatturies</h3>
@foreach(var f in Model.Fakturies)
{
<p>@f.FAK_Numer</p>
}
<h3>Wierszes</h3>
@foreach(var f in Model.Wierszes)
{
<p>@f.Name</p>
}https://stackoverflow.com/questions/38232976
复制相似问题