我想知道是否有人可以帮我构建我的View模型......
我有三个父模型,用户,个人资料和项目
在视图中,我想传递一个包含用户信息,个人资料信息和项目信息的模型......
到目前为止,我的View模型看起来像这样......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ProDevPortMVC3.ViewModels
{
public class PortfolioViewModel
{
public int ProfileID { get; set; }
public int UserID { get; set; }
public string ProfileFirstName { get; set; }
public string ProfileLastName { get; set; }
public string ProfileEmail { get; set; }
public Nullable<long> ProfileContactNo { get; set; }
public string ProfileCity { get; set; }
public string ProfileState { get; set; }
public string ProfileCountry { get; set; }
public string ProfilePhotoPath { get; set; }
public string ProfilePhotoName { get; set; }
public string ProfileBio { get; set; }
public string ProfileMissionStatement { get; set; }
public string ProfilePrivacySetting { get; set; }
public IEnumerable<ProfileBlog> ProfileBlogs { get; set; }
public IEnumerable<ProfileForum> ProfileForums { get; set; }
public IEnumerable<Project> Projects { get; set; }
}
}
问题是Projects模型/表有一对多的子表...我在View模型中也需要他们的所有信息......这里是子表......
ProjectCodeSamples ProjectDownloads ProjectScreenShots ProjectTechnologiesUseds
到目前为止,这是我的控制器操作方法......
public ActionResult Index(int id)
{
var profile = db.Profiles.SingleOrDefault(p => p.UserID == id);
var profileBlogs = db.ProfileBlogs.Where(p => p.ProfileID == profile.ProfileID);
var profileForums = db.ProfileForums.Where(p => p.ProfileID == profile.ProfileID);
var projects = db.Projects.Where(p => p.ProfileID == profile.ProfileID);
var viewModel = new PortfolioViewModel
{
ProfileFirstName = profile.ProfileFirstName,
ProfileLastName = profile.ProfileLastName,
ProfileEmail = profile.ProfileEmail,
ProfileContactNo = profile.ProfileContactNo,
ProfileCity = profile.ProfileCity,
ProfileState = profile.ProfileState,
ProfileCountry = profile.ProfileState,
ProfilePhotoPath = profile.ProfilePhotoPath,
ProfilePhotoName = profile.ProfilePhotoName,
ProfileBio = profile.ProfileBio,
ProfileMissionStatement = profile.ProfileMissionStatement,
ProfilePrivacySetting = profile.ProfilePrivacySetting,
ProfileBlogs = profileBlogs.Where(p => p.ProfileID == profile.ProfileID),
ProfileForums = profileForums.Where(p => p.ProfileID == profile.ProfileID),
Projects = projects.Where(p => p.ProfileID == profile.ProfileID)
};
return View(viewModel);
}
那么,我该如何继续或从这里做什么?
编辑:我忘了添加Project Child Tables有一个外键ProjectID,将它们连接到Projects表...
这是最终的View代码,可以使用...
@foreach (var item in Model.Projects)
{
<p>
@Html.DisplayFor(modelItem => item.ProjectName)
</p>
foreach (var subItem in item.ProjectDownloads)
{
<pre>
@Html.DisplayFor(modelItem => subItem.ProjectDownloadPath)
</pre>
}
}
答案 0 :(得分:0)
由于您在ViewModel中使用Project模型,因此您只需在视图中访问Project的子表。
例如,您应该能够执行以下操作:
foreach(var item in model.Projects)
{
foreach(var download in item.ProjectDownloads)
{
...
}
}