本程式開發環境為visual studio 2010
建立一個MVC 2 的空項目
建好後的目錄結構為如:
既然是MCV,我們關注的就3部分內容。
- Module 資料模組,Module裡主要是一些持久層的Class,通常放在Modules目錄下邊。
- Controller 請求控制器,控制器代碼放Controllers目錄下邊,每個Controller裡包含Action的即Controller裡的方法。每個Controller對應Views下的一個目錄,每個Action對應相應目錄下的檔案。
- View UI呈現部分,構建HTML的相關頁面。放在Views目錄下邊。
模組部分代碼,
~/Models/HelloWorldModule.cs
代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HelloWorld.Models
{
public class HelloWorldModule
{
public string Name
{
get;
set;
}
}
}
建立控制器
~/ Controllers/HelloWorldController.cs 代碼
代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace HelloWorld.Controllers
{
public class HelloWorldController : Controller
{
public ActionResult Hello()
{
return View();
}
}
}
~/Views/HelloWorld/Hello.aspx
代碼
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Hello</title>
</head>
<body>
<div>
<%= ViewData["Message"] %>
<% using (Html.BeginForm())
{%>
<%= Html.TextBox("Name") %>
<input type="submit" value="Hello" />
<%= ViewData["Message1"] %>
<%} %>
</div>
</body>
</html>
編譯後,按CTRL+F5運行,在瀏覽器裡輸入類似,http://localhost:5168/HelloWorld/Hello
最後測試效果