在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>