3

例如,我有 Models: StudentCourse. Student有个List<Course> Courses{get;set;}

所有数据都已从 Web 服务中填充

我有一个Student/Index返回一个 ActionResult 需要一个StudentViewModel 但我也有一个Course/IndexView 返回一个 ActionResult 需要一个CourseViewModel

这应该为我的问题奠定基础:如果我遵循这个选项可以吗,我认为它非常简洁:ViewModelStudent/Index视图中创建 a 的实例

 @foreach(var course in Model.Courses)
    {
       Html.RenderPartial("path/tocourse", 
        new CourseViewModel{Course = course}) ;
    }

或者我应该StudentViewModel有一个List<CourseViewModel>,所以我可以有:

@foreach(var courseViewModel in Model.CourseViewModels)
{
       Html.RenderPartial("path/tocourse", courseviewModel) ;
}

乍一看,上面的内容可能看起来更好,但在Index操作(或其他)中,它需要我执行以下操作:

 new StudentViewModel{
            CourseViewModels = courses.Select(c=>new CourseViewModel{copy stuff}).ToList()
       } 

我讨厌这样,而且它可能会在以后让我或其他开发人员感到困惑,因为看到另一个间接方式让我可以访问 Courses,即StudentViewModel.StudentModel.Courses.

那么哪种方法更好呢?在a 中为此创建 a或 a的实例肯定不会那么糟糕?ViewModelModelView

4

2 回答 2

4

这样做完全没问题。它不被认为是最佳实践。最佳实践是在您的视图中尽可能少地进行处理或实例化。

为了 SOC,我将重构此代码以使用带有子操作方法的 Partials

Html.Action("path/tocourse");

Child Action 将实例化并传递模型,从而减轻您的 View。

[ChildActionOnly]
public ActionResult tocourse()
{

courseviewModel model = new courseviewModel();

    return PartialView(model);
}
于 2013-02-11T23:20:48.190 回答
0

Ideally your view should not have any viewmodel instance logic rather the controller should do all that stuff and give that model to the view. View should be clean. And viewmodel should only have those properties that you need for the view. Now, you can have a model that is complex enough but if you find yourself that a particular model is very complex for your view, just make a viewmodel specific to that view with limited properties that your view needs.

于 2013-02-12T00:08:19.903 回答