Web Forms 与 MVC 的asp.net 基础架构是相同的。MVC 的路由机制并不只MVC 特有的,它与WebForm 也是共享相同的路由机制。Web Forms 的Http请求针对的是物理文件,每个页面都实现IhttpHandler,MVC 的Http 请求是针对Controller的Action方法,最终依靠MvcHandler 实现对请求的响应。由于Web Forms 与MVC 的基础架构相同,所以Web Forms 与 MVC 可以并存在同一个站点下。
实现过程
1. 创建空的Asp.net Web Application
2. 添加 MVC 与Razor 相关的 dll
3. 配置Web.config
![]()
- Form
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MyWebForm.aspx.cs" Inherits="MvcWithWebForm.WebForm.MyWebForm" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvTest" runat="server" >
</asp:GridView>
</div>
</form>
</body>
</html>
- Page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
namespace MvcWithWebForm.WebForm
{
public partial class MyWebForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.BindData();
}
private void BindData()
{
this.gvTest.DataSource = this.GetCustomerList();
this.gvTest.DataBind();
}
public List<Customer> GetCustomerList()
{
List<Customer> list = new List<Customer>();
for (int i = 0; i < 10; i++)
{
Customer c = new Customer() { No = 1000 * i, Name = string.Format("b0b0-{0}",i.ToString()) };
list.Add(c);
}
return list;
}
}
public class Customer
{
public int No
{
get;
set;
}
public string Name
{
get;
set;
}
}
}
5. MVC
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcWithWebForm.Controllers
{
public class CustomerController:Controller
{
public ActionResult Index()
{
return View();
}
}
}
- View
@inherits System.Web.Mvc.WebViewPage
@{
ViewBag.Title = "Index";
}
<h2>MVC Index</h2>
<div>
@for (int i = 0; i < 10; i++)
{
@Html.Raw(string.Format("<div style=\"font-size:{0}pt\"> Hello,Mvc Razor</div>", (5*i).ToString()));
}
</div>
View的位置,必须放到 ~/Views/[Controller]/[ViewName]6. Global 配置 路由规则
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.Mvc;
using RouteDebug;
namespace MvcWithWebForm
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
//全局路由表 忽略掉MVC 对asp.net Web Forms 请求
RouteTable.Routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
//MVC 路由规则
RouteTable.Routes.MapRoute(
"Customer",
"{controller}/{action}/{id}",
new { controller = "Customer", action = "Index", id = UrlParameter.Optional } // 参数默认值
);
}
项目结构
原文:http://www.cnblogs.com/hbb0b0/p/5090301.html