转换模型视图模型 [英] convert model to viewmodel

查看:253
本文介绍了转换模型视图模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表名产品,另一个表名类别。
产品表有的productID,产品名称和类别ID。
分类表中有的categoryID和类别名称。

I have a table name "Product" and another table name "category". Product table has 'productID', 'productName' and 'CategoryID'. Category table has 'categoryID' and 'categoryName'.

我的目标是要显示的产品类别列表。该列表将包含产品编号,产品名称和类别名称。

My target is to display a list of products with category. The list will contain 'product id', 'product name' and 'category name'.

我创建了一个视图模型。在code是

I have created a viewmodel. the code is

public int prodID{get;set;}
public int prodName{get;set;}
public int catName{get;set;}

在我的控制器,我有:

var query= from p in dc.Product
                      select new {p.ProductID,p.ProductName,p.Category1.CategoryName };
var prod = new ProductIndexViewModel()
        {
            ProductList=query //this line is problematic !!it says an explicit conversion exists....
        };
        return View(prod);

怎么会写我的控制器code,使其与视图模型??

How would I write my controller code so that it matches with the viewmodel??

推荐答案

也许你会直接使用您的视图模型类:

Maybe you will use your view model class directly:

       var query = from p in dc.Product
                    select new ProductIndexViewModel() { 
                        prodID = p.ProductID, 
                        prodName = p.ProductName, 
                        catName = p.Category1.CategoryName 
                    };

        List<ProductIndexViewModel> productForView = query.ToList();

这篇关于转换模型视图模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆