Asp.net WebForm架構下添加對Asp.net MVC 的支持
最近要對一些舊項目做功能擴充,需要使用Asp.net MVC架構,但舊項目採用的是webform 架構,現在webform架構基礎
上增加對mvc的支持。
1 下載必備dll文件,并添加到項目的bin目錄下
2 web.config 文件中配置命名空間
3 Global.asax中配置路由
public class Global : System.Web.HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
// 應用程式啟動時執行的程式碼
//全局路由表 忽略掉MVC 对asp.net Web Forms 请求
RouteTable.Routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
RouteTable.Routes.IgnoreRoute("ajaxpro/{*pathInfo}");//忽略掉ajaxpro/相关路由。
RouteTable.Routes.IgnoreRoute("ajax/{*pathInfo}");//忽略掉ajaxpro/相关路由。
//MVC 路由规则
RouteTable.Routes.MapRoute(
"Base",
"{controller}/{action}/{id}",
new { controller = "Base", action = "HelloWorld", id = UrlParameter.Optional } // 参数默认值
);
}
void Application_End(object sender, EventArgs e)
{
// 應用程式關閉時執行的程式碼
}
void Application_Error(object sender, EventArgs e)
{
// 發生未處理錯誤時執行的程式碼
}
void Session_Start(object sender, EventArgs e)
{
// 啟動新工作階段時執行的程式碼
}
void Session_End(object sender, EventArgs e)
{
// 工作階段結束時執行的程式碼。
// 注意: 只有在 Web.config 檔將 sessionstate 模式設定為 InProc 時,
// 才會引發 Session_End 事件。如果將工作階段模式設定為 StateServer
// 或 SQLServer,就不會引發這個事件。
}
}
4 在App_Code文件夾下建立Controller文件夾并建立一個控制器 BaseController
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
namespace WEBSAMPLE1.App_Code.Controllers
{
public class BaseController:Controller
{
public ActionResult HelloWorld()
{
ViewData["Message"] = "Hello World!";
return View("HelloWorld");
}
}
}
5 建立視圖(必須在根目錄下建立Views文件夾)
@inherits System.Web.Mvc.WebViewPage
@{
Layout = null;
}
@{
string a = ViewData["Message"].ToString();
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title></title>
</head>
<body>
<div>
@a
</div>
</body>
</html>
6 運行結果