控制器代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
namespace 显示Demo.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
string strcon = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
string sql = "select * from Product";
public ActionResult Index()
{
using (SqlConnection con = new SqlConnection(strcon))
{
con.Open();
DataSet ds = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter(sql, con);
sda.Fill(ds);
ViewData["getds"] = ds;
}
return View();
}
}
}
视图代码
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<style type="text/css">
table {
border: 2px double red;
}
th {
width: 100px;
}
</style>
</head>
<body>
<div>
<%System.Data.DataSet setds = (System.Data.DataSet)ViewData["getds"];%>
<table id="dt">
<tr>
<th>产品ID</th>
<th>产品名</th>
<th>产品描述</th>
<th>产品URL</th>
<th>价格</th>
<th>ID</th>
</tr>
<%System.Data.DataTable dt = setds.Tables[0]; %>
<%foreach (System.Data.DataRow dr in dt.Rows)
{%>
<tr>
<td><%:dr[0]%></td>
<td><%:dr[1] %></td>
<td><%:dr[2]%></td>
<td><%:dr[3] %></td>
<td><%:dr[4] %></td>
<td><%:dr[5]%></td>
</tr>
<%} %>
</table>
</div>
</body>
</html>