通过多个模型查看 [英] Pass more than one model to view

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

问题描述

 公众的ActionResult指数()
{
    VAR PR = db.products;
    返回查看(PR);
}

首先 - 我要传递给视图更多的数据 - 是这样的:

 公众的ActionResult指数()
{
    VAR PR = db.products;
    变种LR = db.linksforproducts(2)
    返回查看(PR,LR);
}

我如何在视图中阅读 LR 数据?

第二 - 在视图上我有一个产品表,我想这个产品的所有标记添加到表中的列。我如何获得的标签为每一个产品?

现在我创建这个code

 公共类catnewModel
{    公众的IQueryable<类别及GT; DL {搞定;组; }
    公众的IQueryable<产品>医生{搞定;组; }
}

和我的控制器

 公众的ActionResult指数()
    {        VAR PR = db.products;
        VAR PL = db.categories;        catnewModel模式=新catnewModel();
        model.dr = PR;
        model.dl = PL;        返回查看(模型);
    }

在我看来,我尝试遍历

 <%的foreach(在Model.dr VAR项目)%GT;

但我得到的错误

 错误CS1061:'System.Collections.Generic.IEnumerable< amief.Models.catnewModel>'不包含'博士',没有扩展方法的定义


解决方案

我已让视图模型具体到你需要在信息的视图做到了这一点。

然后该视图模型中只是有属性来容纳你的其他车型。

事情是这样的:

 公共类视图模型
{
    公开名单<产品型号>产品(){搞定;组;}
    公开名单< LinksForProductModel> LinksForProducts(){搞定;组;}
}
公众的ActionResult指数()
{
    VAR PR = db.products;
    变种LR = db.linksforproducts(2)    视图模型模型=新视图模型();
    model.Products = PR;
    model.LinksForProducts = LR;
    返回查看(模型);
}

public ActionResult Index()
{ 
    var pr = db.products;
    return View(pr); 
}

Firstly - I want to pass to the view more data - something like:

public ActionResult Index()
{ 
    var pr = db.products;
    var lr = db.linksforproducts(2)
    return View(pr,lr); 
}

How do I read the lr data in the view?

Secondly - on the view I have a table of products, and I want to add to the table a column with all the tags of this products. How do I get the tags for every product?

now i create this code

public class catnewModel
{

    public IQueryable<category> dl { get; set;   }
    public IQueryable<product> dr { get; set;   }
}

and my controller

public ActionResult Index()
    {

        var pr = db.products;
        var pl = db.categories;

        catnewModel model = new catnewModel();
        model.dr = pr;
        model.dl = pl;

        return View(model);
    }

in my view i try to iterate over

 <% foreach (var item in Model.dr)  %>

but i get error on

error CS1061: 'System.Collections.Generic.IEnumerable<amief.Models.catnewModel>' does not contain a definition for 'dr' and no extension method 

解决方案

I have done this by making a ViewModel specific to the view you need the information in.

Then within that ViewModel just have properties to house your other models.

Something like this:

public class ViewModel
{
    public List<ProductModel> Products(){get; set;}
    public List<LinksForProductModel> LinksForProducts(){get; set;}
}


public ActionResult Index()
{ 
    var pr = db.products;
    var lr = db.linksforproducts(2)

    ViewModel model = new ViewModel();
    model.Products = pr;
    model.LinksForProducts = lr;


    return View(model); 
}

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

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