如何在布局中显示多个模型的数据

时间:2014-07-02 17:02:34

标签: asp.net-mvc-4

我想从三个模型Group,Projects和Userprofile中检索数据 我试图创建一个新的类来获取它们,然后将该类称为模型以在布局中使用 但不幸的是没有显示数据..

这是我创建的类,用于将3个模型传递给视图

public class Class1 
{

    public IEnumerable <UserProfile> user {get; set;}
    public IEnumerable<Projects> project { get; set; }
    public IEnumerable <Groups> group{ get; set; }
} 

此处数据应以布局显示

                    <div id="collapseOne" class="panel-collapse collapse in">
                        <div class="panel-body">

                        @if (Model.group != null)
                        {
                            foreach (var d in Model.group) 

                            { 
                                <div class="panel-body">  @d.GroupName</div>
                             }
                        }
                    </div>
                </div>
控制器中的

    databaseDBEntities1 db = new databaseDBEntities1();

    public ActionResult Index(Groups g , Projects P , UserProfile U)
    {
        Class1 c = new Class1();

        return View(c);
    }

2 个答案:

答案 0 :(得分:0)

您在没有设置属性的情况下传递空对象:

 public ActionResult Index(Groups g , Projects P , UserProfile U)
    {
        Class1 c = new Class1();
        c.user  = U;
        c.project = P;
        c.group =  g;

        return View(c);
    }

或:

public class Class1 
{

    public List<UserProfile> user {get; set;}
    public list<Projects> project { get; set; }
    public List<Groups> group{ get; set; }
} 

 public ActionResult Index()
        {
            Class1 c = new Class1();
            c.user  = db.UserProfile.ToList();
            c.project = db.Projects.ToList();
            c.group =  db.Groups.ToList();

            return View(c);
        }

答案 1 :(得分:0)

您需要在Class1中设置Groups,Projects和UserProfile。

databaseDBEntities1 db = new databaseDBEntities1();
Class1 c = new Class1();
c.user = db.UserProfile();
c.project = db.Projects();
c.group = db.Groups();
return View(c);

如果索引方法现在已经是这个实体,你可以设置这个属性,就像@ehsan mansion一样。

Class1 c = new Class1();
c.user  = U;
c.project = P;
c.group =  g;