一.创建一个基本类型的MVC4项目.
二.创建HomeController:
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using StrongViewDemo.Models;
namespace StrongViewDemo.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
public ActionResult OneInt()
{
//1.
int a = 1;
return View(a);
//2.
//return View(1);
}
public ActionResult OneBoxInt()
{
BoxInt bi = new BoxInt();
bi.OneInt = 1;
return View(bi);
}
public ActionResult ManyInt()
{
List<int> list = new List<int>();
for (int i = 0; i <= 5; i++)
{
list.Add(i * 2 + 1);
}
return View(list);
}
public ActionResult ManyBoxInt()
{
List<BoxInt> list = new List<BoxInt>();
for (int i = 0; i <= 5; i++)
{
BoxInt bi = new BoxInt();
bi.OneInt = i * 2 + 1;
list.Add(bi);
}
return View(list);
}
}
}
除了首页,增加了4个Action分别来发送一个整数,一个对象,一个整数列表,一个对象列表。下方我们将创建了4种Stong View,来接收这4种数据.
三.在Models目录下创建BoxInt类
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace StrongViewDemo.Models
{
public class BoxInt
{
public int OneInt { set; get; }
}
}
四.在Views目录下创建5个Action相对应的View:
首页Index有其他4个的链接,对应4种Stong View,来接收上述Aciton发送的4种数据.
代码如下:
Index.cshtml:
@{
ViewBag.Title = "Index";
}
<h2>Strong View Demo</h2>
<h2>@Html.ActionLink("One Int","OneInt")</h2>
<h2>@Html.ActionLink("One BoxInt","OneBoxInt")</h2>
<h2>@Html.ActionLink("Many Int","ManyInt")</h2>
<h2>@Html.ActionLink("Many BoxInt","ManyBoxInt")</h2>
OneInt.cshtml:
@model int
@{
ViewBag.Title = "OneInt";
}
<h2>OneInt</h2>
<h2>@Model</h2>
OneBoxInt.cshtml:
@model StrongViewDemo.Models.BoxInt
@{
ViewBag.Title = "OneBoxInt";
}
<h2>OneBoxInt</h2>
<h2>@Model.OneInt</h2>
ManyInt.cshtml:
@model List<int>
@{
ViewBag.Title = "ManyInt";
}
<h2>ManyInt</h2>
@foreach (var i in Model)
{
@i
<hr />
}
ManyBoxInt.cshtml:
@model IEnumerable<StrongViewDemo.Models.BoxInt>
@{
ViewBag.Title = "ManyBoxInt";
}
<h2>ManyBoxInt</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.OneInt)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.OneInt)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</table>
五.小结:
列表里面如果是基本数据类型,那么Strong View,既可以采用List<int>,也可以采用 IEnumerable<int>来声明Strong View;列表里面如果不是普通的基本数据类型,而是对象类型,View只能采用 IEnumerable<对象类型> 来声明Strong View。