http://www.cnblogs.com/chrischen662/archive/2010/08/13/1798876.html
MVC架構已深得人心,微軟也不甘落後,推出了Asp.net MVC,並在vs2010中已經內建了MVC的相關功能。如果使用vs2008,需要下載安裝Service Pack 1和ASP.NET MVC Framework。MVC現在已經是2.0的版本。
選擇相關開發語言,建立一個 ASP.NET MVC Web Application 項目,選擇不需要單元測試,這樣產生了一個MVC架構,按Ctrl+F5運行,可看到一個歡迎首頁。
注意:使用MVC後不是按連結檔案來訪問頁面,而是通過控制器實現路由連結。
我們通過一個簡單的增刪查改的功能來體會一下MVC開發的過程。
第一步:模組開發
首先我們建立一個簡單的表格:test,該表格只有兩個欄位:id和name。並建立一個資料類,在Models檔案夾中建立一個類,代碼如下:
代碼
//Test.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcWeb.Models
{
public class Test
{
private int _id = -1;
public int id
{
get { return _id; }
set { _id = value; }
}
public String name {get;set;}
}
}
然後在Models檔案夾中建立一個檔案夾:Maping,在此檔案中建立一個LINQ to Sql,將test表拖進設計器中,儲存。
最後在Models檔案夾中建立一個類:TestModel.cs,輸入如下代碼:
代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Linq;
using MvcWeb.Models.Maping;
namespace MvcWeb.Models
{
public static class TestModel
{
private static TestDbMapingDataContext testDb = new TestDbMapingDataContext();
//返回記錄總數
public static int Count()
{
return testDb.test.Count();
}
//分頁列表
public static List<Test> GetList(int page, int pageSize)
{
var query = (from c in testDb.test orderby c.id ascending select c).Skip((page - 1) * pageSize).Take(pageSize);
List<Test> result = new List<Test>();
foreach (var t in query)
result.Add(FillRecord(t));
return result;
}
//列表
public static List<Test> GetList()
{
var query = (from c in testDb.test orderby c.id ascending select c);
List<Test> result = new List<Test>();
foreach (var t in query)
result.Add(FillRecord(t));
return result;
}
//修改和插入儲存
public static long Save(Test myTest)
{
try
{
test t = (from c in testDb.test where c.id == myTest.id select c).FirstOrDefault();
if (t == null)
{
t = new test();
t.id = myTest.id;
t.name = myTest.name;
testDb.test.InsertOnSubmit(t);
}
else
{
t.name = myTest.name;
}
testDb.SubmitChanges();
return t.id;
}
catch(ChangeConflictException ce)
{
testDb.ChangeConflicts.ResolveAll(RefreshMode.OverwriteCurrentValues);
testDb.SubmitChanges();
}
return -1;
}
//刪除記錄
public static bool Delete(int id)
{
try
{
test t = (from c in testDb.test where c.id == id select c).FirstOrDefault();
testDb.test.DeleteOnSubmit(t);
testDb.SubmitChanges();
return t != null;
}
catch (ChangeConflictException ce)
{
testDb.ChangeConflicts.ResolveAll(RefreshMode.OverwriteCurrentValues);
testDb.SubmitChanges();
}
return false;
}
//取一條記錄
public static Test GetItem(int id)
{
test t = (from c in testDb.test where c.id == id select c).FirstOrDefault();
return FillRecord(t);
}
//構造資料對象
private static Test FillRecord(test i)
{
Test result = null;
if (i != null)
{
result = new Test();
result.id = i.id;
result.name = i.name;
}
return result;
}
}
}
第二步:控制器開發
在Controllers檔案夾中右鍵選擇Controller,將產生一個控制器,將檔案名稱改為:TestController.cs,並將代碼做些修改,以訪問模組:
代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcWeb.Models;
namespace MvcWeb.Controllers
{
public class TestController : Controller
{
//
// GET: /Test/
int pageSize = 3;
public ActionResult Index(int page)
{
if (page * pageSize > TestModel.Count()) page = page - 1;
if (page <= 0) page = 1;
ViewData["page"] = page;
var model = TestModel.GetList(page, pageSize);
return View(model);
}
//
// GET: /Test/Details/5
public ActionResult Details(int id)
{
var model = TestModel.GetItem(id);
return View(model);
}
//
// GET: /Test/Create
public ActionResult Create()
{
Test mytest = new Test();
return View(mytest);
}
//
// POST: /Test/Create
[HttpPost]
public ActionResult Create(int id,FormCollection collection)
{
try
{
// TODO: Add insert logic here
Test mytest = new Test();
UpdateModel(mytest, collection.ToValueProvider());
if(mytest.name == null)
ViewData.ModelState.AddModelError("name", "userName not specified.");
if (!ViewData.ModelState.IsValid)
throw new InvalidOperationException();
TestModel.Save(mytest);
return RedirectToAction("Index?page=1");
}
catch(InvalidOperationException ex)
{
return View(new Test());
}
}
//
// GET: /Test/Edit/5
public ActionResult Edit(int id)
{
var model = TestModel.GetItem(id);
return View(model);
}
//
// POST: /Test/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
Test mytest = new Test();
UpdateModel(mytest, collection.ToValueProvider());
TestModel.Save(mytest);
return RedirectToAction("Index?page=1");
}
catch
{
return View();
}
}
//
// GET: /Test/Delete/5
public ActionResult Delete(int id)
{
var model = TestModel.GetItem(id);
return View(model);
}
//
// POST: /Test/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
TestModel.Delete(id);
return RedirectToAction("Index", new { page = 1 });
}
catch
{
return View();
}
}
}
}
第三步:視圖開發
在控制器的Index方法中按右鍵,選擇“Add View”,作出如的選擇:
即在Views/Test檔案夾下面產生一個視圖:Index.aspx,因為我們使用了分頁設計,所以在檔案後面加上如代碼:
<%= Html.ActionLink("Create New", "Create") %>
<% =Html.ActionLink("<< 前一頁", "Index", new { page = (int)ViewData["Page"] - 1 })%>
<% =Html.ActionLink("後一頁 >>", "Index", new { page = (int)ViewData["Page"] + 1 })%>
開啟Views/Home/Index.aspx,加入一個對Test頁面的連結:
<%= Html.ActionLink("測試", "Index?page=1", "Test")%>
按上面的方法在控制器的Create, Edit, Delete產生相關視圖,因為首頁使用了分頁,所以要將返回首頁的連結“Back to List”,略作修改:“Index?page=1”。我們可以看看產生的Create.aspx的代碼:
代碼
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcWeb.Models.Test>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Create
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Create</h2>
<% using (Html.BeginForm()) {%>
<%= Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%= Html.LabelFor(model => model.id) %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.id) %>
<%= Html.ValidationMessageFor(model => model.id) %>
</div>
<div class="editor-label">
<%= Html.LabelFor(model => model.name) %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.name) %>
<%= Html.ValidationMessageFor(model => model.name) %>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%= Html.ActionLink("Back to List", "Index?page=1") %>
</div>
</asp:Content>
完成任務,按Ctrl+F5運行,在首頁上點擊“測試”,即可體驗增刪查改的功能。