一、在Global.asax.cs添加新的Route
1 routes.MapRoute(
2 "NewsRoute",
3 "{controller}/{action}/{id}", // URL with parameters
4 new { controller = "News", action = "Index", id = UrlParameter.Optional } // Parameter defaults
5 );
二、添加所需Controller
在/Controllers/ 添加NewsController,複選框打勾,建立Create、Update、Delete、Details方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVC2Demo.Controllers
{
public class NewsController : Controller
{
//
// GET: /News/
public ActionResult Index()
{
return View();
}
//
// GET: /News/Details/5
public ActionResult Details(int id)
{
return View();
}
//
// GET: /News/Create
public ActionResult Create()
{
return View();
}
//
// POST: /News/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /News/Edit/5
public ActionResult Edit(int id)
{
return View();
}
//
// POST: /News/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /News/Delete/5
public ActionResult Delete(int id)
{
return View();
}
//
// POST: /News/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
三、添加Model
在Models添加ADO.NET Entity Data Model(在對應的開發語言下的Data模板裡)
接下來的介面中選擇【generate from database】,然後就是串連到資料庫選擇表,並將資料庫連接儲存到web.config中,根據嚮導一步步來就行,不贅述了。
四、在/Views/下添加News檔案夾,然後添加相應的Views,右鍵菜單——Add——View
1)新聞列表
通過在下面介面的中做些配置,可以很容易產生相應的View,然後根據需要修改就好。
產生的View是使用Table布局的,在CSS+DIV遍天下的今天,微軟在這裡為什麼不使用呢?
2)添加
參1)
3)瀏覽
參1)
4)修改
參1)
5)刪除
參1)
PS:這裡有個小插曲,昨天我建好Model後,在View data class列表中居然找不到建立的Model,試了好多次,重啟也無果,本來打算手寫了,可今天Model又出現在列表裡了,#@¥#%¥……%#!#
五、在主版頁面(Master Page)中添加新聞欄目
運行後,看到的介面如下:
我們在【Home】後面添加【News】,在/Views/Shared/可以找到Site.Master
開啟主版頁面,添加如下代碼(中間的News)
<div id="menucontainer">
<ul id="menu">
<li><%: Html.ActionLink("Home", "Index", "Home")%></li>
<li><%: Html.ActionLink("News", "List", "News")%></li>
<li><%: Html.ActionLink("About", "About", "Home")%></li>
</ul>
</div>
運行後就可以在頁面的右上方看到在【Home】和【About】之間多了【News】。
下篇主要開始介紹代碼實現部分的內容。