如何在mvc 4中的一个视图中传递两个模型列表?

时间:2014-12-02 11:48:53

标签: asp.net-mvc-4

我的问题是列表<>,我在控制器操作方法的两个列表中取两个模型它在两个列表中传递值但是它不能在视图中传递两个列表值,我在下面给出我的代码,请给一些解决方案。

    projet name Myproject,

    my model,

    public class table1
    {
      public int id {get;set;}
      public string student_name {get;set;}
    }
    public class table2
    {
      public int id {get;set;}
      public string roll_number {get;set;}
    }

    my controller page,

    list<table1> t=new list<table1>();
    list<table2> t1=new list<table2>();
    public ActionResult details()
    {
       sqlDataAdapter da=new sqldataAdapter("select * from Table1",con);
       dataset ds=new dataset();
       da.fill(ds);
       foreach(datarow dr in ds.Table[0].row)
       {
         t.add(new table1()
          {
            id=int.parse(dr[0].ToString()),
            student_name=dr[1].ToString()
          }
       }

       sqlDataAdapter da1=new sqldataAdapter("select * from Table2",con);
       dataset ds1=new dataset();
       da1.fill(ds1);
       foreach(datarow dr1 in ds1.Table[0].row)
       {
         t1.add(new table2()
          {
            id=int.parse(dr1[0].ToString()),
            roll_number=dr1[1].ToString()
          }
       }

       return details(t,t1);
    }

    view   \\\\\\\\\\\\\\\\ My problem in view ,plase help me this problem.

    @using MultiSelectList;
    @model  List<Myproject.Models.table1>
    @model  List<Myproject.Models.table2>


    @{
        ViewBag.Title = "Details";
    }

    <h1>Welcome to details page</h1>

1 个答案:

答案 0 :(得分:2)

这很容易。创建一个包含2个列表的类。

public class CustomModel
    {
        public List<table1> Table1 { get; set; }

        public List<table2> Table2 { get; set; }
    }

然后在控制器中返回CustomModel

return details(t,new CustomModel { Table1 = t1, Table2 = t2 });

在视图中

@model  Myproject.Models.CustomModel