我会做一些非常接近的事情:
模型
public QuestionViewModel : IQuestionViewModel
{
public QuestionModel : Question { get; set; }
}
public IQuestionViewModel
{
QuestionModel: Question { get; }
}
public QuestionModel : IAnswersViewModel, ICommentsViewModel, IUserViewModel
{
public string Title { get; set; }
public string Summary { get; set; }
public IENumerable<Tag> Tags { get; set; }
public UserModel User { get; set; }
public IEnumerable<AnswerModel> Answers { get; set; }
public IEnumerable<CommentModel> Comments { get; set; }
}
public IAnswersViewModel
{
IEnumerable<AnswerModel> Answers { get; }
}
public ICommentsViewModel
{
IEnumerable<CommentModel> Comments { get; }
}
public IUserViewModel
{
UserModel User { get; }
}
public AnswerModel : ICommentsViewModel, IUserViewModel
{
public Summary { get; set; }
public UserModel { get; set; }
public IEnumerable<CommentModel> Comments { get; set; }
}
public CommentModel : IUserViewModel
{
public string Summary { get; set; }
public UserModel User { get; set; }
}
public UserModel
{
public string Name { get; set ; }
}
控制器
public class QuestionController : Controller
{
public ActionResult Details(int QuestionID)
{
// Populate the model as you see fit
// I normally have my models populate themselves
// So I don't duplicate code in my controllers
QuestionViewModel model = QuestionViewModel.Get(QuestionID)
if (model == null)
{
return this.UnavailableQuestion()
}
return this.View(model);
}
// Questions that don't exist
public ActionResult UnavailableQuestion
{
return this.View();
}
}
** 观看次数(全部非常简化)**
问题\Details.cshtml
@Model IQuestionViewModel
@model.Question.Title
@model.Question.Summary
@html.Partial("partial-UserComplex", model.Question)
@html.Partial("partial-Comments", model.Question)
@html.Partial("partial-Answers", model.Question);
Shared\partial-UserComplex.cshtml
@Model IUserViewModel
//Complex might display details like points, etc etc
@model.User.Name
Shared\partial-UserSimple.cshtml
@Model IUserViewModel
//Simple would just have a name with a link to profile
@model.User.Name
Shared\partial-Comments.cshtml
@Model ICommentsViewModel
@foreach (CommentModel comment in model.Comments)
{
@comment.Summary
@Html.Partial("partial-UserSimple", comment)
}
问题\partial-Answers.cshtml
@Model IAnswersViewModel
@foreach (AnswerModel answer in model.Answers)
{
@answer.Summary
@Html.Partial("partial-UserComplex", answer)
@Html.Partial("partial-Comments", answer)
}
优点
- 每个 View/PartialView 都使用一个界面,因此我可以创建任意数量的不同模型并重复使用相同的视图。
- 由于显示评论(也许?)和用户将遍布整个网站,我可以轻松地重用共享目录中的部分内容
- 显示答案、评论和用户完全相互分离。
- 非常可扩展。
缺点
- 在视图中使用接口有点复杂,因为您想要添加的任何新内容都必须添加到接口以及继承该接口的任何类。
- 根据子类的数量和模型的重用,这相当复杂。