对于我的管理应用程序,我在我的modelfolder中有一个包含实体的dbml文件(例如person,company,address,contact,...)
在mvc的帮助下,我可以处理目前为止的所有CRUD操作,但只能处理1个实体。 现在我想在人体实体的1个视图信息中显示联系人和地址实体的相应信息。实体已经与正确的关系连接。
我该如何有效地做到这一点?
答案 0 :(得分:6)
您需要创建一个ViewModel,用于保存实际视图中所需的每个实体的信息。
例如,我有一个名为PublicationsController的控制器,它将在我的Web应用程序中构建一个目录页面。一个ActionResult需要向我的View提供一个名为PublicationsListViewModel的ViewModel。
PublicationsListViewModel:
public class PublicationsListViewModel
{
public IList<Publication> Publications { get; set; }
public PagingInfo PagingInfo { get; set; }
public String CurrentCategory { get; set; }
public Dictionary<String, String> SelectedItems { get; set; }
}
如您所见,PublicationsListViewModel只是每个需要传递给我的View的实体的容器。
My PublicationsController看起来像这样:
<强>控制器:强>
public ActionResult List(Cart cart, string category, int page = 1)
{
Dictionary<String, String> selectedItems = new Dictionary<String, String>();
foreach (var line in cart.Lines)
{
selectedItems.Add(line.Publication.PDFID.ToString(), line.Quantity.ToString());
}
foreach (var line in cart.Lines)
{
ViewData.Add(line.Publication.PDFID.ToString(), line.Quantity.ToString());
}
var publicationsToShow = (category == null)
? publicationsRepository.Publications
: publicationsRepository.Publications.Where(x => x.Category.Equals(category, StringComparison.CurrentCultureIgnoreCase));
var viewModel = new PublicationsListViewModel
{
Publications = publicationsToShow.Skip((page - 1) * PageSize).Take(PageSize).ToList(),
PagingInfo = new PagingInfo
{
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = publicationsToShow.Count()
},
CurrentCategory = category,
SelectedItems = selectedItems
};
return View(viewModel); // Passed to view as ViewData.Model (or simply Model)
}
我的视图看起来像这样
查看:强>
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<myNameSpace.WebUI.Models.PublicationsListViewModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Publications : <%: Model.CurrentCategory ?? "All Publications" %>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<%
foreach (var publication in Model.Publications)
{
Html.RenderPartial("PublicationSummary", publication, ViewData);
}
%>
<div class="pager">
<%: Html.PageLinks(Model.PagingInfo, x => Url.Action("List", new { page = x, category = Model.CurrentCategory }))%>
</div>
</asp:Content>