Tuesday, September 4, 2012

Sending dataset from controller to View in MVC3

In this example i used Access database as backend so worked with oledb client..if ur backend is SQL just change the connection string and Oledb with SQL remaing code ie same.

In your controller

   public ViewResult Index()
        {
            OleDbConnection cn = new OleDbConnection("provider=microsoft.ace.oledb.12.0;data source=e:/database1.accdb;");
            OleDbDataAdapter  DA = new OleDbDataAdapter ("select * from emp",cn);
          
            cn.Open();
         
            DataSet ds = new DataSet();
            DA.Fill(ds);
            cn.Close();
         
            return View(ds);
           
        }


In your View


   


        @model  System .Data .DataSet (this is very important ,tha purpose of this is ..it will tell to Model that recieved data is dataset)

               @foreach (System .Data .DataRow row  in Model .Tables [0].Rows )
               {
                 //It will give result based on no of rowcloumns we added. Below we added 2 columns
                   @(row[0]+"  "+row[1])
                  

                 
                  
                 // it will give result all columns automatically
                   for (int i = 0; i < row.ItemArray.Length; i++)
                   {
                       @(row [i]+" ")
                 
                   }
                   

               }
   

2 comments:

Anonymous said...

Hello. And Bye. Thank you very much.

Anonymous said...

Hello. And Bye. Thank you very much.