[英]Display multiple models in a single view
我必须创建一个发票视图。 我有许多模型(表),并且我想在一个发票视图中显示多个模型的所有数据。 我创建了一个空(无模型)视图,并放入了局部视图。 部分视图之一返回具有一个模型的一个视图,但是该解决方案使我异常...这是我的工作:这是我在控制器中的动作:
public ActionResult Customer()
{
var data = db.Customer;
return PartialView("Index", data);
}
public ActionResult Invoice()
{
var data = db.Invoice;
return PartialView("Index", data);
}
public ActionResult Dealer()
{
var data = db.Dealer;
return PartialView("Index", data);
}
public ActionResult Paid()
{
var data = dane.Paid;
return PartialView("Index", data);
}
public ActionResult Products()
{
var data = dane.Products;
return PartialView("Index", data);
}
这是部分视图之一:
@model IEnumerable<Invoice_v1._0.Models.Products>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Price)
</th>
<th>
@Html.DisplayNameFor(model => model.Amount)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.DisplayFor(modelItem => item.Amount)
</td>
</tr>
}
</table>
这是我的带有部分视图的“索引”视图:
@Html.Partial("_Customer")
@Html.Partial("_Invoice")
@Html.Partial("_Dealer")
@Html.Partial("_Paid")
@Html.Partial("_Products")
我该如何解决?
如果您坚持拥有单个视图,则可以使部分视图的渲染成为条件:
if (Model != null && Model is Customer)
Html.Partial("_Customer", Model as Customer)
, 等等。
值得一提的是,由于所有模型都是互斥的(您永远不会有多个对象),所以我看不到拥有一个Index视图的意义。 每个类已经有一个(局部)视图,那么为什么不只将它们用作常规视图呢?
更新资料
如果选择从每个操作方法返回单独的视图,则可以通过指定每个视图的名称来实现。 有关详细信息,请参阅此问题: 如何使用特定的View(而不是控制器名称)返回ActionResult。
在您的特定情况下,这意味着:
public ActionResult Customer()
{
return View("_Customer", db.Customer);
}
public ActionResult Invoice()
{
return View("_Invoice", db.Invoice);
}
public ActionResult Dealer()
{
return View("_Dealer", db.Dealer);
}
public ActionResult Paid()
{
return View("_Paid", db.Paid);
}
public ActionResult Products()
{
return View("_Products", db.Products);
}
确保每个视图都需要强类型模型。 这将使实现视图变得容易。
尽管您的方法可行,但您对数据的控制较少或没有控制(如果要假设联接或使用任何父数据)。 在这种情况下,我要做的是创建一个包含多个对象的ViewModel。 例如
public class InvoiceViewModel
{
public InvoiceHead Header { get;set; }
public IList<InvoiceDetail> Details { get; set; }
}
因此,现在我可以在进入视图之前填充此视图模型。
public ActionResult Invoice(int id)
{
InvoiceViewModel viewModel = new InvoiceViewModel();
viewModel.Header = db.InvoiceHead.SingleOrDefault(i => i.ID == id);
if(viewModel.Header != null)
{
viewModel.Details = db.Details.Where(d => d.Inv_id == id).ToList();
}
return View(viewModel);
}
现在,我可以为发票数据设计局部视图或整体视图。
我将把IEnumerable或IList作为模型
如果我都使用了partial,那么它将是@model db.Objects.InvoiceHead //
@model IEnumerable //详细信息
在HTML代码将是这样的
@Html.Partial("~/Views/Customers/_AttachFileList.cshtml")
使用您自己的文件夹路径。 希望有效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.