我要学ASP.NET MVC 3.0(八): MVC 3.0 传递和保存你的Model
概述
?
在 ASP.NET MVC 框架中,模型(Model)是負責核心應用程序或業(yè)務邏輯的應用程序部件。 模型對象通常從諸如 SQL Server 之類的永久存儲區(qū)(如數(shù)據(jù)庫)中訪問數(shù)據(jù),并對該數(shù)據(jù)執(zhí)行業(yè)務邏輯。
模型特定于應用程序,因此 ASP.NET MVC 框架對您可以生成的模型對象的種類沒有限制。 例如,您可以使用 ADO.NET DataSet 或 DataReader 對象,或者可以使用一組自定義的域對象。 您也可以使用對象類型的組合來處理數(shù)據(jù)。總之:處理數(shù)據(jù)的辦法是多樣的只要您選擇適合您的其中一種即可。
模型不是特定的類或接口。 類是模型的一部分,這并不是因為它可以實現(xiàn)某接口或派生自某基類。 而是由于類在 ASP.NET MVC 應用程序中發(fā)揮的作用,以及類在應用程序文件夾結構中的存儲位置的緣故。 ASP.NET MVC 應用程序中的模型類不直接處理來自瀏覽器的輸入,也不生成到瀏覽器的 HTML 輸出。
?
定義模型
?
模型對象是實現(xiàn)域邏輯(也稱為業(yè)務邏輯)的應用程序部件。 域邏輯可處理在數(shù)據(jù)庫與 UI 之間傳遞的數(shù)據(jù)。 例如,在庫存系統(tǒng)中,模型將跟蹤存儲區(qū)中的物品以及用于確定庫存中是否有某個物品的邏輯。 此外,模型將是在物品賣出并從倉庫中發(fā)貨時對數(shù)據(jù)庫進行更新的應用程序部件。 通常,模型還將在數(shù)據(jù)庫中存儲和檢索模型狀態(tài)。
?
集成模型和控制器
?
通常我們創(chuàng)建Model都是在?ASP.NET MVC 應用程序模板中 Visual Studio 提供的 Models 文件夾中創(chuàng)建。
但是,通常也會將模型類存放在單獨的程序集中,比如單獨的類庫,以便我們可以在不同的應用程序中重復使用這些類。
MVC中Model和View的分離,使應用程序的邏輯元素保持分離,這樣就可以輕松地測試應用程序邏輯,而不必通過用戶界面測試該邏輯。
?
創(chuàng)建Model
?
右擊MVC項目中的Model文件夾--> 選擇添加-->類
將其命名為Person
?添加類代碼
public class Person{
/// <summary>
/// 編號
/// </summary>
public int ID { get; set; }
/// <summary>
/// 姓名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 年齡
/// </summary>
public int Age { get; set; }
}
?好了 目前我們一個簡單的Model已經(jīng)添加好了 但是我們還沒有使用他,下面我們接著來學習如何使用該Model。
?
列表頁面
創(chuàng)建PersonController
鼠標右擊Controller文件夾-->添加控制器
?程序默認生成了Index方法,明眼的你一眼就能發(fā)現(xiàn),該方法要返回的View還沒有創(chuàng)建,所以我們創(chuàng)建他對應的View
右擊該方法---選擇添加視圖
?點擊添加后,可以看到,VS已經(jīng)給我們把PersonList的Razor視圖代碼都寫好了。。。(*^__^*) 嘻嘻愉快。。。
?迫不及待了 點擊運行。。。哦哦 看不到Person的主頁
此時我們可以把Global.asax里面的默認controller改為Person即可。或者做導航。。后面介紹
?代碼如下
routes.MapRoute("Default", // 路由名稱
"{controller}/{action}/{id}", // 帶有參數(shù)的 URL
new { controller = "Person", action = "Index", id = UrlParameter.Optional } // 參數(shù)默認值
);
?再次運行。。。繼續(xù)報錯。。Model未將對象。。。實例
回頭想想 其實是我們沒有給View傳送數(shù)據(jù)而已。。
那么我們給他一個模擬數(shù)據(jù)。這里也可以從數(shù)據(jù)庫讀取!!!
Controller代碼
/// <summary>/// 獲取數(shù)據(jù)
/// </summary>
/// <returns>PersonList</returns>
IEnumerable<Person> GetData()
{
IEnumerable<Person> list = new List<Person>
{
new Person() {ID = 1001, Name = "張三", Age = 20},
new Person() {ID = 1002, Name = "李四", Age = 22}
};
return list;
}
//
// GET: /Person/
public ActionResult Index()
{
return View(GetData());
}
?修改后的View代碼
@model IEnumerable<MvcApplication.Models.Person>@{
ViewBag.Title = "人員列表";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>
人員列表</h2>
<table>
<tr>
<th>
姓名
</th>
<th>
年齡
</th>
<th>
</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@item.Name
</td>
<td>
@item.Age
</td>
<td>
@Html.ActionLink("修改", "Edit", new { id = item.ID }) |
@Html.ActionLink("明細", "Details", new { id = item.ID }) |
@Html.ActionLink("刪除", "Delete", new { id = item.ID })
</td>
</tr>
}
</table>
<p>
@Html.ActionLink("創(chuàng)建人員", "Create")
</p>
?運行效果
?
明細頁面
Controller代碼
//// GET: /Person/Details/5
public ActionResult Details(int id)
{
foreach (var person in GetData())
{
if (person.ID.Equals(id))
{
return View(person);
}
}
return View();
} View代碼 @model MvcApplication.Models.Person
@{
ViewBag.Title = "人員明細";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>人員明細</h2>
<fieldset>
<legend>人員信息</legend>
<div class="display-label">姓名:</div>
<div class="display-field">@Model.Name</div>
<div class="display-label">年齡:</div>
<div class="display-field">@Model.Age</div>
</fieldset>
<p>
@Html.ActionLink("編輯", "Edit", new { id=Model.ID }) |
@Html.ActionLink("返回列表", "Index")
</p>
運行效果
?創(chuàng)建人員 在PersonController新建Create方法 //// GET: /Person/Create
public ActionResult Create()
{
return View();
}
創(chuàng)建視圖
生成的視圖代碼
@model MvcApplication.Models.Person@{
ViewBag.Title = "創(chuàng)建人員";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>
創(chuàng)建人員</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<legend>人員信息</legend>
<div class="editor-label">
@Html.LabelFor(model => model.ID)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ID)
@Html.ValidationMessageFor(model => model.ID)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Age)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Age)
@Html.ValidationMessageFor(model => model.Age)
</div>
<p>
<input type="submit" value="創(chuàng)建" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("返回列表", "Index")
</div>
雖然有了 頁面有了初始方法
但是我們還沒有寫他的數(shù)據(jù)保存方法。。。
繼續(xù)在PersonController里面寫Create方法不過這次要在方法上面加上[HttpPost]確保該方法只能在界面發(fā)送數(shù)據(jù)的時候執(zhí)行。
//初始化視圖// GET: /Person/Create
public ActionResult Create()
{
return View();
}
//只用于接受頁面發(fā)過來的Http請求
// POST: /Person/Create
[HttpPost]
public ActionResult Create(Person person)
{
try
{
//操作數(shù)據(jù)的代碼
return RedirectToAction("Success",person);
}
catch
{
return View();
}
}
/// <summary>
/// 用于顯示添加人員成功
/// </summary>
/// <param name="person"></param>
/// <returns></returns>
public string Success(Person person)
{
return "刪除用戶成功!姓名:"+person.Name;
}
因為我們沒有和數(shù)據(jù)庫交互,所以跳轉到了一個Success的方法,輸出成功語句。。
運行效果
點擊創(chuàng)建之后
?
修改人員信息
與新增頁面類似我們創(chuàng)建修改的初始頁面Edit
//初始頁面// GET: /Person/Edit/5
public ActionResult Edit(int id)
{
return View();
} 添加視圖
生成的代碼
@model MvcApplication.Models.Person@{
ViewBag.Title = "修改人員";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>
修改人員</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<legend>人員信息</legend>
@Html.HiddenFor(model => model.ID)
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Age)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Age)
@Html.ValidationMessageFor(model => model.Age)
</div>
<p>
<input type="submit" value="保存" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("返回列表", "Index")
</div> 添加保存代碼,還是繼續(xù)返回上面的Success方法 //初始頁面
// GET: /Person/Edit/5
public ActionResult Edit(int id)
{
return View();
}
//修改方法
// POST: /Person/Edit/5
[HttpPost]
public ActionResult Edit(int id, Person person)
{
try
{
// 數(shù)據(jù)庫操作代碼
return RedirectToAction("Success",person);
}
catch
{
return View();
}
} 運行效果 點擊保存后
?
刪除人員
在PersonController中添加方法
//// GET: /Person/Delete/5
public ActionResult Delete(int id)
{
return View();
}
添加刪除視圖
生成的視圖代碼
@model MvcApplication.Models.Person@{
ViewBag.Title = "刪除人員";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>
刪除人員</h2>
<h3>
你確定要刪除該人員?</h3>
<fieldset>
<legend>人員信息</legend>
<div class="display-label">
編號</div>
<div class="display-field">@Model.ID</div>
<div class="display-label">
姓名</div>
<div class="display-field">@Model.Name</div>
<div class="display-label">
年齡</div>
<div class="display-field">@Model.Age</div>
</fieldset>
@using (Html.BeginForm())
{
<p>
<input type="submit" value="刪除" />
|
@Html.ActionLink("返回列表", "Index")
</p>
}
添加刪除代碼
//// GET: /Person/Delete/5
public ActionResult Delete(int id)
{
foreach (var person in GetData())
{
if (person.ID.Equals(id))
{
return View(person);
}
}
return View();
}
//
// POST: /Person/Delete/5
[HttpPost]
public string Delete(int id, Person person)
{
return "已刪除編號為" + id + "的人員";
}
?運行效果
點擊刪除
?
總結
MVC開發(fā)基本步驟
一:添加Model對應的Controller
二:在Controller創(chuàng)建操作Model的方法
三:根據(jù)創(chuàng)建的方法添加視圖,并選擇視圖模板等
四:修改VS生成的視圖代碼,如加CSS樣式等操作
五:添加按鈕的Post方法,必須以該視圖名稱命名,參數(shù)不能和初始化視圖的參數(shù)一樣。
六:調(diào)試代碼。
?
下節(jié)預告
MVC 3.0 數(shù)據(jù)有效性之Model驗證
作者:記憶逝去的青春
出處:http://www.cnblogs.com/lukun/
本文版權歸作者和博客園共有,歡迎轉載,但未經(jīng)作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,如有問題,可以通過http://www.cnblogs.com/lukun/ ?聯(lián)系我,非常感謝。
轉載于:https://www.cnblogs.com/lukun/archive/2011/07/29/2120699.html
總結
以上是生活随笔為你收集整理的我要学ASP.NET MVC 3.0(八): MVC 3.0 传递和保存你的Model的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 三星显示 2.18 亿美元收购美国 Mi
- 下一篇: 233小游戏密室逃脱攻略