为了简单起见。该示例中省略M层的描述,直接通过VC两层来实现.Net web编程中的表格基本绘制实现
新建一个MVC项目(我用的是visual studio 2017)
我用的是一个包含模板MVC工程,新建之初就具备很完善的页面形态。
在实际网页设计中,模板的使用可以为我们节省很多时间,带来不少的便利。
我们就在该模板的一个About页面里用表格的形式展现“九九乘法口诀表”
“About”页面位于"HomeController.cs"中
控制器修改
原About函数
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
修改后的About函数
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
string[,] val = new string[10, 10];
for (int i = 1; i < 10; i++)
val[i, 0] = val[0, i] = i.ToString();
for(int i=1;i<10;i++)
for(int j=i;j<10;j++)
{
val[i, j] = i + "*" + j + "=" + (i * j);
}
return View(val);
}
通过比较,不难看出,修改后的函数中,我是通过数组的方式写入了“九九乘法表”,并通过传参给View(),将数据送到视图上。
视图修改
原视图代码
@{
ViewBag.Title = "About";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
修改后的视图代码
@{
ViewBag.Title = "About";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
<p>九九乘法表</p>
@{
string[,] val = (string[,])Model;
int Rows = val.GetLength(0);
int Cols = val.GetLength(1);
}
<table class="table">
<caption class="caption">九九乘法表格</caption>
<thead >
<tr>
@{
for (int c = 0; c < Cols; c++)
{
<td>@val[0, c]</td>
}
}
</tr>
</thead>
@{
for(int r=1;r<Rows;r++)
{
<tr>
@{
for(int c=0;c<Cols;c++)
{
<td>@val[r,c]</td>
}
}
</tr>
}
}
</table>
两个代码的区别也一目了然,代码中,我们首先获取控制器传来的数组参数,
@{
string[,] val = (string[,])Model;
int Rows = val.GetLength(0);
int Cols = val.GetLength(1);
}
其中“@”是Razor语法的一部分。主要作用是可以让您将基于服务器的代码(Visual Basic 和 C#)嵌入到网页中。可以点击链接查看详细信息
ASP.NET Razor 标记 | 菜鸟教程www.runoob.com紧接着就是创建HTML表了,该部分的原型是
<table border="1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>
除却样式部分,就比较Html标签的构成方式,可以理解出C#从内存数据表转换为页面表的过程,实际就是通过Razor语句自动补充Html表格单元格标签的过程。
于是我们简单的网页九九乘法表就这么造好了。
将程序仿web表原型细微改写下
<table class="table">
<caption class="caption">九九乘法表格</caption>
<thead >
<tr>
@{
for (int c = 0; c < Cols; c++)
{
<th>@val[0, c]</th>
}
}
</tr>
</thead>
@{
for(int r=1;r<Rows;r++)
{
<tr>
@{
for (int c = 0; c < Cols; c++)
{
if (c > 0)
{
<td>@val[r, c]</td> }
else
{
<th>@val[r, c]</th> }
}
}
</tr>
}
}
</table>
能看出区别吗
HTML 表格标签总结
<table>:表示是一个表
<caption>:为表写一个标题
<tr>:表内的一行
<td>:单元格元素,文本通常是普通的左对齐文本。
<thead>:表格的表头部分,此外还有<tbody> 和 <tfoot>
<th>:表头元素,文本通常呈现为粗体并且居中。