I am new to MVC and trying to write a simple MVC 3 application which reads customer data inside a class in model and return it to view using controller. Reader shows it has rows but when load to table and pass to view as model, it is null. I need a simple solution to pass either a DataTable
to view or DataReader
to view where I can convert to DataTable
.
Here is the code:
namespace MvcApplication3.Models
{
public class Customer
{
public DataTable GetCustomers(OdbcDataReader rds)
{
String ConString = "DSN=Northwind;Uid=;Pwd=;";
String SQL = "SELECT * FROM CUSTOMERS";
DataTable tbl = new DataTable();
using (OdbcConnection con = new OdbcConnection(ConString))
{
con.Open();
OdbcCommand cmd = new OdbcCommand(SQL, con);
rds = cmd.ExecuteReader();
}
}
}
}
namespace MvcApplication3.Controllers
{
public class DefaultController : Controller
{
//
// GET: /Default1/
public ActionResult Index()
{
Customer cs = new Customer();
OdbcDataReader rd = new OdbcDataReader();
cs.GetCustomers(rd);
DataTable tb = new DataTable();
tb.Load(rd);
return View(tb);
}
}
}
for the controller :
public ActionResult Index()
{
DataTable dt = GetData();
return View(dt);
}
Then in the view :
@model System.Data.DataTable
@using System.Data;
.................. .............. ........
<table class="table table-hover">
<thead>
<tr>
@foreach (DataColumn col in Model.Columns)
{
<th>@col.ColumnName</th>
}
</tr>
</thead>
<tbody>
@foreach (DataRow row in Model.Rows)
{
<tr>
@foreach (DataColumn col in Model.Columns)
{
<td>@row[col.ColumnName]</td>
}
</tr>
}
</tbody>
</table>
A view in mvc is always associated with a strongly typed model I.e a class..so in your case..just create a class with a list..while fetching data insert that data into a list and pass that class into the view..
class A {
public string name{get;set;}
public int age{get;set;}
}
//code when fetching data
//this list should be in the class where you fetch the data
Public list<A> list=new list<A>();
while(datareader.read)
{
A Aobj=new A();
String name=reader['name'].tostring();
int age =Convert.ToInt(reader['age']);
A.name=name;
A.age=age;
list.add(A);
}//end of while loop
//action resut
public ViewResult yourview(){
Return View(list);
}
//now you can access the data from the view.
By....
@model IEnumerable<A>
//here A is your class name
@foreach(var data in Model){
<div>@data.age</div>
}
Sorry for the code format... posted from mobile
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With