ViewModel是否将逻辑计数设置为"不需要的逻辑"在控制器中

时间:2014-05-09 06:03:46

标签: c# asp.net asp.net-mvc n-layer

那么Controller的下一个示例是否有效?或者像这样的逻辑应该在别的地方? 据我所知,我们需要使用DTO在图层之间传输数据,因此如果我们从JsonResult图层传递ViewModelBussinesLogic,它会出错吗? 那么这个例子正确,专用于ViewModel创建的逻辑可以在controller

        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult UploadImage(HttpPostedFileBase file)
        {
            var result = UploadedImageHandler.UploadFile(file);
            JsonResult json;

            if (result != null)
            {
                var uploadImageViewModel = new UploadedImagesViewModel
                {
                    foo = result.foo
                    //here some values from result goes to ViewModel
                };
                var uploadResult = new UploadResultViewModel
                {
                    Preview = new PreviewViewModel 
                    {
                        bar = result.bar 
                        //etc.
                    },
                    UploadedImage = uploadImageViewModel
                };
                json = new JsonResult
                {
                    Data = uploadResult,
                    ContentType = "text/html"
                };
            }
            else
            {
                json = new JsonResult
                {
                    ContentType = "text/html"
                };
            }

            return json;
        }

1 个答案:

答案 0 :(得分:1)

对我来说是正确的。

ViewResult和JsonResult都是特定于表示层的东西,而不是实际的业务逻辑,因此属于控制器。

一些额外的(理论上的)思考:技术,在纯MVC原则下,控制器甚至不应该知道它呈现的是哪种视图(json或html),以及部分技术上应该由另一个MVC Action Filter处理。但是在大多数现实场景中(在.NET世界中),这种模式很少被使用,而你上面的内容最常见(因此我们甚至有类似JsonResult等的东西)。所以它可能不是很重要。但是,即使您以这种方式构建它,Action Filter仍然会在Web层(MVC项目)中,而不是在业务层中。

但是,是的,任何专用于ViewModel的逻辑应始终位于控制器(“web”/表示层)中,而不应位于业务层中。业务层甚至不应该知道ViewModel存在(在理想情况下,业务层将是一个完全不知道您的Web MVC程序集的单独程序集,甚至不会看到这些类)。然后,您将从业务层传回“业务对象”(也称为“域”对象),然后将其转换为控制器内的ViewModel(仅特定于演示文稿)并将其传递到观点。