分享

MVC模式在ASP.NET中的应用

 liuqg 2006-03-16

介绍

在网上搜寻了很长时间后却不能够找到一个演示ASP.NET的MVC模型的例子. 于是我实现了一个很好的能够领略

MVC模型的简单实例.

有关 MVC

在一个传统的应用程序中,一个单一代码要处理所有事物。 藉由MVC模型,你可以将你的应用程序有机的分成三个协作的部份: 模型,视图和控制器。视图是直接面向用户使用的部份。它格式化数据使数据以各种形式展现在荧屏上。然而实际上,它不包含数据。数据包容在模型中。最后,控制器部分接受用户操作命令进而

修正模型内的数据。更多的有关MVC方面的知识可以到下面的连接

http://www./1999/papers/webmvc_part1.html

模型

假定你知道MVC模型, 我要给你的这一个例子将演示如何在ASP.NET中实现MVC模式。

模型是你所有的商业逻辑代码片段所在。我这里给出一个类实现二个数字相加,并把结果送回用户界面。

using System;

namespace MVCTest

{

/// This class is where we have the business logic build in.

/// It is a managed library that will be referenced by

/// your web application

public class Model

{

public Model()

{

}

// static method for adding two numbers

//

// @params int a,b - numbers to be added

// @return c - result

public static int Add(int a, int b)

{

int c = a + b;

return c;

}

// static nethod to add two numbers

//

// @params string a,b - numbers to be added

// @return int c - result

public static int Add(string a, string b)

{

int c = Int32.Parse(a) + Int32.Parse(b);

return c;

}

}

}

控制器

在ASP.NET中,你通常直接地请求服务。取代身为子控制器的一个服务,它是我们进入ASP.NET应用程序的主要切入点。这里不提供的一个中心的位置判断你是否有权限使用该服务, 或者也不提供任何其他的通常应该在所有的服务中发生的处理。然而, 使你所有的与aspx关联的各个类继承一个通用的System.Web.UI.Page子类, 你就可以放置这些全部的预先处理代码到覆盖了Page类的OnLoad()方法中。OnLoad()会在每次页面被装载的时候被.Net框架调用。在你的与aspx代码关联的类中调用Page_Load()方法之前, 这里可以让你作为一个中心位置验证服务是否被允许使用以及做一些重定向, 这里你可以使用Server.Transfer()就好象真的中央控制器一样。我命名了我的视图控制类Controller。一旦你必须在显示任何的aspx页面之前验证登录信息或为用户做一些初始的操作, 那么这些都可以组合到OnLoad()方法中。

现在,不管什么在地方当你的在应用程序中要重定向或者连接到一个aspx页面时候,你将使用GetServicePage()方法取得要跳转的文件名字。如果你已经重新命名网页来重整你的网站,你立刻会发现这样意义深远的简化了维护工作。如果要你重新命名一个aspx文件, 现在你可以重新命名该文件并改

变GetServicePage的中的命名对, 这样你的网站仍能继续工作。

using System;

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Web;

using System.Web.SessionState;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

namespace MVCApplication

{

/// This class acts as a controller extends System.Web.UI.Page. This class

/// maintains all the information about your web pages and performs any pre-requiste

/// conditions.

public class Controller : System.Web.UI.Page

{

private int id = 0;

//enum ViewPages has the information of all the aspx pages in your site

// it is represented as a name value pair.

public enum ViewPages

{

View1 = 1, View2, View3

}

public int ServiceId

{

get

{

return id;

}

set

{

id = value;

}

}

/// Method used for getting the name of the page by providing

/// its reference number.

/// @param int page_id - a number to retrieve the page name.

/// @return string page - name of the aspx page.

public string GetServicePage(int page_id)

{

//Get the page name by passing the number from enum

string page = Enum.GetName(typeof(ViewPages), page_id);

return page;

}

// Could implement pre-requiste condition in this method

override protected void OnLoad(EventArgs e)

{

}

private void Page_Load(object sender, System.EventArgs e)

{

}

#region Web Form Designer generated code

override protected void OnInit(EventArgs e)

{

//

// CODEGEN: This call is required by the ASP.NET Web Form Designer.

//

InitializeComponent();

base.OnInit(e);

}

/// <summary>

/// Required method for Designer support - do not modify

/// the contents of this method with the code editor.

/// </summary>

private void InitializeComponent()

{

this.Load += new System.EventHandler(this.Page_Load);

}

#endregion

}

}

视图

这里有我们所有的aspx页面及其支援的对应类代码片段。例子中我使用了2个aspx页面。一个是为取得用户为使用两个数字相加而输入的两个数字,而另一个则为用户返回显示结果。

这里是View1.aspx页面的原代码

-----------------------------------

<%@ Page language="c#" Codebehind="View1.aspx.cs" AutoEventWireup="false"

Inherits="MVCApplication.View1" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >

<html>

<head>

<title>View1</title>

</head>

<body MS_POSITIONING="GridLayout">

<h3>ADDITION</h3>

<form runat="server" ID="Form" method="post">

<table>

<tr valign="middle">

<td class="field">First Number</td>

<td>

<asp:textbox id="one" runat="server"

columns="32" maxlength="32" />

</td>

</tr>

<tr valign="middle">

<td class="field">Second Number</td>

<td>

<asp:textbox id="two" runat="server"

columns="16" maxlength="16" />

</td>

</tr>

<tr>

<td colspan="2" align="center">

<asp:button id="btnSubmit" runat="server"

text="Add" onClick="Submit" cssclass="button" />

</td>

</tr>

</table>

</form>

</body>

</html>

这下面是View1.aspx.cs的代码

---------------------------------------------------

using System;

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Web;

using System.Web.SessionState;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

using MVCTest;

namespace MVCApplication

{

/// This is our View in the MVC model. This class is a sub class of Controller.

/// This class gets the input from the View1.aspx page, calls the add method in

/// Model class and sends to the next aspx page.

public class View1 : Controller

{

/// The next screen to send on the case of success.

/// Id of the screen as is in the Controller

private int Next_Screen = 2;

/// The screen to send on the case of failure/error.

/// Id of the screen as is in the Controller

private int Failure_Screen= 3;

protected TextBox one;

protected TextBox two;

protected HtmlForm Form;

protected Button btnSubmit;

public View1()

{

ServiceId = 1;

}

/// Get the number to be added from the user, perform the operation

/// and send the result.

protected void Submit(object sender, System.EventArgs e)

{

if(Page.IsValid)

{

string first = one.Text;

string second = two.Text;

int sum = Model.Add(first, second);

//Get the page name from the Controller

string page_path = GetServicePage(Next_Screen);

Server.Transfer(page_path+".aspx?sum="+ sum.ToString());

}else {

//On failure direct to this screen

Server.Transfer(GetServicePage(Failure_Screen));

}

}

private void Page_Load(object sender, System.EventArgs e)

{

}

#region Web Form Designer generated code

override protected void OnInit(EventArgs e)

{

//

// CODEGEN: This call is required by the ASP.NET Web Form Designer.

//

InitializeComponent();

base.OnInit(e);

}

/// <summary>

/// Required method for Designer support - do not modify

/// the contents of this method with the code editor.

/// </summary>

private void InitializeComponent()

{

this.Load += new System.EventHandler(this.Page_Load);

}

#endregion

}

}

以下是View2.aspx的原文件

----------------------

This page gets the result as a request parameter and displays it.

<%@ Page language="c#" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >

<%@ Import Namespace="System.Web" %>

<%@ Import Namespace="System.Web.SessionState" %>

<%@ Import Namespace="System.Web.UI" %>

<%@ Import Namespace="System.Web.UI.WebControls" %>

<%@ Import Namespace="System.Web.UI.HtmlControls" %>

<script language="C#" runat="server">

void Page_Load(Object sender, EventArgs e)

{

Label1.Text = Request.Params.Get("sum");

}

</script>

<html>

<head>

<title>View2</title>

</head>

<body MS_POSITIONING="GridLayout">

<h3>SUM</h3>

<asp:Label id="Label1" Runat="server"></asp:Label>

<form id="View2" method="post" runat="server">

</form>

</body>

</html>

结论

我希望这一个例子将会帮助你体会MVC模型的架构。这里提供的例子代码仅仅是演示如何实现这一模型架构, 而在实际的应用中通常会用一个配置文件来替换这个固定的GetServerPage(), 我之所以选择了这个只是为了保持代码的简洁。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多