model-view-controller - 将模型转换为 View 模型

标签 model-view-controller asp.net-mvc-3 viewmodel

这个问题在这里已经有了答案:





Where to convert business model to view model?

(3 个回答)


3年前关闭。




我有一个表名“产品”和另一个表名“类别”。
产品表有“productID”、“productName”和“CategoryID”。
类别表具有“categoryID”和“categoryName”。

我的目标是显示带有类别的产品列表。该列表将包含“产品 ID”、“产品名称”和“类别名称”。

我创建了一个 View 模型。代码是

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

在我的 Controller 中,我有:
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);

我将如何编写 Controller 代码以使其与 View 模型匹配??

最佳答案

您可以使用 AutoMapper而不是从 db 模型重写属性。

var viewModel = new ProductIndexViewModel()
{  
    ProductList = dc.Product.ToList().Select(product => Mapper.Map<Product, ProductViewModel>(product));
}

关于model-view-controller - 将模型转换为 View 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7312012/

相关文章:

JavaFX 从另一个线程更新 UI

ios - 我应该使用尽可能多还是尽可能少的 View / View Controller ?

wpf - 如何将ViewModel应用于页面内的UserControl?

c# - MVC模型中Controller的作用是什么?

database - var data = Database.Open ("databasename").Query("SELECT * FROM table); visual studio

asp.net-mvc - 如何在显示模板中显示下拉列表的选定文本而不是选定值?

css - 在页面加载时更改文本框的颜色

javascript - Knockoutjs - 在使用 foreach 而不是选项时丢失了选择值的两种绑定(bind)方式

android - 使用 Android 导航组件在底部导航中的多个 fragment 之间共享 View 模型

java - Controller 是否创建新 View ?