在MVC模型中,控制器与视图之间的数据传输可以通过ViewBag,例如@ViewBag.Keleyi
也可以使用模型类实现强类型传输,例如:
@model Keleyi.Com.Model.MessageInfo
这是在KeleyiCMS项目中,回复留言是采用的方法。
KeleyiCMS是一个开源项目,是用功能强大和现在热门的ASP.NET MVC和Entity Framework搭建。更多信息请访问http://keleyi.com/menu/cms/
强类型的好处是可以在编译的时候就进行赋值的检查,如果赋值类型不匹配的话,编译器将报错,这就保证了类型的安全性。详细可以参考泛型:http://keleyi.com/a/bjac/dd5020768bf34110.htm
而且在强类型的视图中,Visual Studio能够对Model的各种成员做出丰富的代码提示,我们便可以快速地输入代码,并确保不会出现“拼写”之类的低级错误。
那么怎样创建强类型视图呢?
在要添加视图的控制器的代码中,
点击右键,在弹出菜单中选择“添加视图”
在弹出“添加视图”对话框中,勾选“创建强类型视图”,然后选择模型类是支架模板。如果在模型类中看不到你要的类型,则可以编译后再试试。
源代码下载: http://keleyi.codeplex.com
附一个视图的代码:
@model Keleyi.Com.Model.MessageInfo @{ ViewBag.Title = "回复留言"; } <h2>回复留言</h2> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>MessageInfo</legend> <div class="display-label"> @Html.DisplayNameFor(model => model.kID) </div> <div class="display-label"> @Html.TextBoxFor(model => model.kID, new { @readOnly = "readOnly", @style = "background:silver" }) </div> <div class="display-label"> @Html.DisplayNameFor(model => model.kTitle) </div> <div class="display-field"> @Html.TextBoxFor(model => model.kTitle, new { @readOnly = "readOnly", @style = "background:silver" }) </div> <div class="display-label"> @Html.DisplayNameFor(model => model.kContent) </div> <div class="display-field"> @Html.TextAreaFor(model => model.kContent, new { cols=20,rows=3, @readOnly = "readOnly", @style = "background:silver" }) </div> <div class="display-label"> @Html.DisplayNameFor(model => model.kEmail) </div> <div class="display-field"> @Html.TextBoxFor(model => model.kEmail, new { @readOnly = "readOnly", @style = "background:silver" }) </div> <div class="display-label"> @Html.DisplayNameFor(model => model.kQQ) </div> <div class="display-field"> @Html.TextBoxFor(model => model.kQQ, new { @readOnly = "readOnly", @style = "background:silver" }) </div> <div class="editor-label"> @Html.DisplayNameFor(model => model.kAddtime) </div> <div class="editor-label"> @Html.TextBoxFor(model => model.kAddtime, new { @readOnly = "readOnly",@style="background:silver" }) @Html.ValidationMessageFor(model => model.kAddtime) </div> <div class="editor-label"> @Html.DisplayNameFor(model => model.kIsshow) </div> <div class="editor-field"> @Html.EditorFor(model => model.kIsshow) </div> <div class="editor-label"> @Html.LabelFor(model => model.kReply) </div> <div class="editor-field"> @Html.TextAreaFor(model => model.kReply, new { rows = 5, cols = 10 }) @Html.ValidationMessageFor(model => model.kReply) </div> <p> <input type="submit" value="保存" /> @ViewBag.Result </p> </fieldset> } <div> @Html.ActionLink("返回列表", "Index", "MessageAdmin") </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") } <script type="text/javascript" src="http://keleyi.com/keleyi/pmedia/jquery-1.9.1.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $("#kReply").focus(); }) </script>