在asp.net mvc 中使用datatable方法:
1,首先在 control 中加入action 方法:
public ActionResult ListCountryInfo(string id)
{
string sql = "select * from country_info";
dsTest.country_infoDataTable dt = new dsTest.country_infoDataTable();//强类型datatable
using (SqlConnection myConnection = new SqlConnection(AppConfiguration.ConnectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(sql, myConnection);
myCommand.CommandType = CommandType.Text;
SqlDataAdapter adapter = new SqlDataAdapter(myCommand);
adapter.Fill(dt);
}
return View(dt);
}
2,对应视图中的代码,如下
@using MvcDemo.Models.DS //引用 强类型datatable的namespace,如果直接使用datatable,则引用 System.Data namespace即可
@using System.Data
@model dsTest.country_infoDataTable //改视图使用的 强类型datatable,如果直接使用datatable,则不用此行
@{
ViewBag.Title = "ListCountryInfo";
}
<h2>ListCountryInfo</h2>
<table>
<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>