在ASP.NET中实现Model-View-Presenter(MVP)

asp.net MVP模式简单实现(被动视图) ASP.NET 的MVP模式简单实现,采用被动视图,简单起见Model层没有依赖注入实现,但是已经预留了层次,有后续版本全功能实现 立即下载

介绍

我在ASP.NET中使用MVP设计模式已经一年有余,在此之前我在一个使用事件驱动实现的SmartClient应用程序中第一次接触到了MVP模式,与富客户端环境相比,将MVP模式应用到Web环境仍然存在一些问题。本文将介绍这些问题,并提供我认为针对ASP.NET具有最大可用性和可测试性的实现方式。

本文将介绍MVP模式的基础以及在ASP.NET中的3中实现方式,让读者了解在各种不同的实现方式中
 ASPX页面,ASCX用户控件和Presenter的不同功能,该模式在ASP.NET中没有一种完全正确的实现方式,具体采用何种方式完全取决于个人喜好。

ASP.NET中的Model-View-Presenter

ASP.NET默认采用的Page Controller模式对应用程序分层和测试都没有提供良好的支持,对ASP.NET运行时的依赖使得测试必须在实际的应用场景中才可以顺利进行,我们要寻找一种更好的模式以针对不同的视图页提高测试效率,MVP就是这样一种方式。

Model-view-presenter旨在应用程序分层和提高测试效率,它的主要目标是将显示逻辑与业务逻辑分离,正如我们设计面向对象程序中创建松散耦合并可重用的对象。为了实现该目的,我们针对各种不同的业务创建不同的类和层,例如:View, presentation, service和data-access。在ASP.NET中很容易将这种业务逻辑添加到页面或用户控件类中,但同时造成紧耦合并降低了可重用性和测试效率。MVP通过使用presenter层将显示逻辑和控制逻辑相分离。

MVP的另一个目标是提高针对View的测试效率。编写依赖Session, ViewState, AJAX, HTML或web控件和业务实体的单元测试类较为复杂,因此我们将各视图的显示逻辑保留在ASPX/ASCX文件类中,并将业务逻辑从中分离出来放在相应的类中,在MVP中Presenter充当视图和业务逻辑的缓冲层。

Martin Fowler将MVP模式分为主动控制(Supervising Controller)和被动控制(Passive Controller)两种,不同于真正的MVC(Model-View-Controller)框架针对View和Presentation(Controller)进行严格的区分,因为在ASP.NET中这种划分默认是不被强化的。it is difficult to enforce any one implementation of MVP without conscientious effort on the part of the developer, and the grey area between implementing a Supervising Controller and a Passive View widens. 我在创建Presenter时的原则是从View中剥离出尽可能多的希望进行测试的代码并放在presenter中,view只负责处理各自的诸如Javascript, HTML和WebControls, AJAX框架的代码,因此在我的View中仍然有一些逻辑代码,我将该种方式界定为主动控制被动视图(Supervising Controller versus Passive View), 在几个不眠之夜之后终于在ASP.NET中实现了主动控制方式。

如果你需要了解更多信息,下面的连接或许会有所帮助:

GUI Architectures
Supervising Controller
Passive View
Presenter First
Model View Presenter with ASP.NET
ASP.NET Supervising Controller (Model View Presenter) From Schematic To Unit Tests to Code

ASP.NET中MVP的不同实现方式

在ASP.NET中实现MVP模式时,我的设计融合了多种思路,一种来自于Billy McCafferty另一种来自Phil Haack。因为我是通过一个事件驱动的windows应用程序了解到MVP因此我采用自己更为熟悉的事件驱动方式来实现。Web的无状态特性是我需要克服的第一个障碍。在ASP.NET中我们需要在客户端与服务器的每一次返送中借助IsPostBack属性重建MVP关系来实现状态持久化。示例代码中演示了我们如何通过传入IsPostBack值来重建presenter的方式解决该问题。MVP在ASP.NET中的实现方式有很多种,而具体选择某种方式完全取决于个人喜好,我偏好的实现方式包含了上面提到的两位作者的思路以及我自己的一些发现。

下面将分为3 部分介绍,一部分介绍每种实现方式。我将从介绍ASP.NET中的MVP开始,然后介绍事件驱动的实现方式,最后我介绍第三种我认为复用性更高的实现方式。示例代码包含了每一种实现方式,代码中的每一个模块应用了不同的实现方式,下面的代码并不完整而只是表明基本的工作原理。

第一种实现方式

第一种实现方式是Billy McCafferty提出的,该方式将ASPX的功能定义为“视图初始化和页面定位”。ASCX用户控件作为View,presenter只知道描述View的接口,ASPX页面只负责初始化presenter和传入需要的View和model对象,并将presenter绑定到view,因此view在必要的时候要引用Presenter。最后,页面调用presenter的InitView方法模拟ASP.NET中的PostBack事件。

"Product"模块采用该方式实现。

public   class  Presenter
{
    
public Presenter(IView view, IModel model)
    
{
        
this.view = view;
        
this.model = model;
    }


    
public void InitView(bool isPostBack)
    
{
        
if(!isPostBack)
        
{
            view.SetProducts(model.GetProducts());
        }

    }

    
    
public void SaveProducts(IList<IProduct> products)
    
{
        model.SaveProducts(products);
    }

}


The ASPX Page: The Starting Point
The ASPX HTML references the ASCX user control, and 
in  code behind we have  this .

protected   override   void  OnInit(EventArgs e)
{
    
base.OnInit(e);
    presenter 
= new Presenter(view,model);
    view.AttachPresenter(presenter);
    presenter.InitView(Page.IsPostBack);
}


The ASCX User Control
public   void  AttachPresenter(Presenter presenter)
{
    
this.presenter = presenter;
}


public   void  SetProducts(IList < IProduct >  products)
{
    
// bind products to view
}


// The View Interface
public   interface  IView
{
    
void AttachPresenter(Presenter presenter);
    
void SetProducts(IList<IProduct> products);
}

 第二种实现方式

第二种实现方式是事件驱动的方式,该方式同样将ASPX的作用定义为视图初始化和页面定向。ASCX用户控件实现了供Presenter使用的事件的View接口,View与Presenter无关而只需要触发事件,ASPX初始化Presenter并传递给View和Model对象。ASPX页面不负责将Presenter绑定到View也不调用Presenter的"InitView”方法,它只负责将Presenter传递给View和Model实例,并处理Presenter可能触发的诸如页面定向或其他事件。

“Customer”模块采用该中方式实现。

Note: The code below  is  used to highlight the main points of  this  design. Please see the sample application  for  a working model.


The Presenter
public   class  Presenter
{
    
public Presenter(IView view, IModel model)
    
{        
        
this.view = view;
        
this.model = model;
        
        
this.view.OnViewLoad += new EventHandler<SingleValueEventArgs<bool>>(OnViewLoadListener);
        
this.view.SaveProducts += new EventHandler<SingleValueEventArgs<IList<IProduct>>>(SaveProductListener);
    }

    
    
private void OnViewLoadListener(object sender, SingleValueEventArgs<bool> isPostBack)
    
{
        
if (!isPostBack.Value)
        
{
            
// Set the view for the first time
            view.SetProducts(model.GetProducts());
        }

    }

    
    
private void SaveProductListener(object sender, SingleValueEventArgs<IList<IProduct>> products)
    
{
        model.SaveProducts(products.Value);
    }

}


The ASPX Page: The Starting Point
The ASPX HTML references the ASCX user control, and 
in  code behind we have  this .

protected   override   void  OnInit(EventArgs e)
{
    
base.OnInit(e);
    presenter 
= new Presenter(view,model);
}


The ASCX User Control
protected   override   void  OnLoad(EventArgs e)
{
    EventHandler eventHandler 
= OnViewLoad;
    
if (eventHandler != null)
    
{
        
// Invoke our delegate
        eventHandler(this, new SingleValueEventArgs<bool>(Page.IsPostBack));
    }


    
base.OnLoad(e);
}

    
public   void  SetProducts(IList < IProduct >  products)
{
    
// bind products to view
}


protected   void  btnSave_Click( object  sender, EventArgs e)
{
    
// Raise our event
    OnSaveProducts(GetProducts());
}


public   event  EventHandler < SingleValueEventArgs < string >>  SaveProducts;

public   virtual   void  OnSaveProducts(IList < IProduct >>  products)
{
    EventHandler
<SingleValueEventArgs<IList<IProduct>>> eventHandler = SaveProducts;
    
if (eventHandler != null)
    
{
        eventHandler(
this, new SingleValueEventArgs<IList<IProduct>>(products));
    }

}


The View Interface
public   interface  IView
{
    
event EventHandler OnViewLoad;
    
event EventHandler<SingleValueEventArgs<IList<IProduct>>>SaveProducts; 
    
void SetProducts(IList<IProduct> products);
}

第三种实现方式

该方式将创建Presenter,传递View和model,调用“InitView”方法的功能交给ASCX用户控件(View)处理。View应用相应的Presenter,Presenter只知道View的接口。ASPX页只用于添加用户控件,因此只需要将用户控件拖拽到页面上可以很容易的重用。

“Employee"模块采用该种方式实现。

Note: The code below  is  used to highlight the main points of  this  design. Please see the sample application  for  a working model.


The Presenter
public   class  Presenter
{
    
public Presenter(IView view, IModel model)
    
{        
        
this.view = view;
        
this.model = model;
    }


    
public void InitView(bool isPostBack)
    
{
        
if(!isPostBack)
        
{
            view.SetProducts(model.GetProducts());
        }

    }

    
    
public void SaveProducts(IList<IProduct> products)
    
{
        model.SaveProducts(products);
    }

}


The ASPX Page
The ASPX HTML references the ASCX user control, nothing futher 
in  code behind.

The ASCX User Control: The Starting Point
protected   override   void  OnInit(EventArgs e)
{
    
base.OnInit(e);
    presenter 
= new Presenter(this,model);
    presenter.InitView(Page.IsPostBack);
}


public   void  SetProducts(IList < IProduct >  products)
{
    
// bind products to view
}


The View Interface
public   interface  IView
{
    
void SetProducts(IList<IProduct> products);
}

 

Reflecting on the Implementations

每种方式各有千秋,没有真正的ASP.NET MVP框架,因此实现方式的选择由个人偏好决定。

我倾向于前两种方式中的将ASPX作“视图初始化和页面定向”使用,因为这种方式使ASPX不会只是作为ASCX的一个载体,我认为View应该只负责与View相关的功能,如何界定View相关的功能也是一个值得商榷的问题。

在第二种实现方式中,我喜欢View与Presenter无关的设计方式,View与Presenter解耦并只负责触发事件,“OnViewLoad"作为第一个事件标志控件的加载状态并传入页面的IsPostBack属性,Presenter侦听该事件并命令View执行一些操作。ASPX实例化Presenter,传入View和Model实例并根据需要注册Presenter的事件。

我不喜欢前两种方式主要是因为由于ASPX页面被调用,因此ASCX重用需要更多的工作,如果希望将用户控件添加到一个新页面上,我需要实例化Model-View-Presenter关系。这在用户控件中包含用户控件时将会变得繁琐。将该部分功能由ASPX页面迁移至ASCX控件可以解决该问题,这样View拥有了更复杂的功能,但可重用性也更加提升。虽然我并不十分同意该种方式,但它却是提高了重用性,代码类也依然可以测试。

虽然我喜欢通过事件驱动的方式将Prsenter与View解耦,但这并不是必须的。使用事件并不总是直观可可靠的,而且针对是事件编写单元测试也更加复杂,而且也不能保证Presenter可以订阅到View上的所有事件。

After settling my philosophical debates and finally feeling comfortable with certain responsibilities of the ASPX page, ASCX user control, and presenter in ASP.NET, I have created this third implementation. This third implementation is similar to the first implementation but it omits the role of the ASPX "view initializer and page redirector." On the positive side, my view is more reusable across my application since it is more self reliant. On the negative side, my view now has the added responsibility of creating the presenter and responding to events the presenter may raise. Even though I may feel that certain responsibilities are crossing boundaries, I keep reminding myself that this is MVP in ASP.NET - this is not a true MVC framework that enforces that good separation of concerns like Monorail.

Conclusion


MVP provides a number of advantages, but to me, the two most important are separation of concerns and testability. There is a fair amount of overhead involved in using MVP, so if you are not planning on writing unit tests, I would definitely reconsider using the pattern.

As we see with the three different implementations, there are numerous ways to implement the pattern in ASP.NET. There are even more ways than what I have chosen to display. Choose an implementation that best suits your needs. I have to work hard at implementing MVP in ASP.NET, and there are certain tradeoffs I need to be willing to accept. As long as my code is testable, reusable, maintainable, and there exists a good degree of separation of concerns, I am happy.

With Microsoft's news of releasing an MVC framework for ASP.NET, there is hope on the horizon for a framework that enforces good separation of concerns and testability. The Castle Project's Monorail is another MVC framework that I highly recommend. If you cannot wait for Microsoft's MVC framework, or do not wish to port your application to Monorail at this time, then implementing MVP could be your answer.

About the Sample Project
The sample project is written in ASP.NET 2.0 using C#. I am using the Northwind database. I am using SubSonic as my data access layer. Since SubSonic is built using the active record pattern, I do have to use interfaces in order to make my DAO classes testable. For my unit testing, I am using RhinoMocks as my mocking framework.

The sample application is comprised of five projects. The WebApp, Model, Presentation layer, Presentation.Tests, and SubSonic data access layer. This sample is simplistic and should be used as a demo. I may be doing some things in code for the sake of brevity and to simplify the concepts. This is my disclaimer for not providing "production" code with all the frameworks, tools, and layers I typically create. 

 

[Asp.Net]MVP Demo 功能上没有多写什么.UI上仅有一个DDL的读取.然后SysFramework中的一些BaseClass也留TODO,这些大家可以根据自己口味去实现吧.Demo重点不是想演示太多的细节实现,而只是想表达整个架构. 数据库用的sql自带示例数据库:Northwind 数据访问层用的是:NHibernate Projects 说明: AspNetMVPDemoApp.DataAccess(数据访问层) AspNetMVPDemoApp.DataAccess.Interface(数据访问接口) AspNetMVPDemoApp.Model(MVP中的M) AspNetMVPDemoApp.Presenter(MVP中的P) AspNetMVPDemoApp.View.Interface(MVP中的V的接口) AspNetMVPDemoApp.SysFramework(System Framework核心层) AspNetMVPDemoApp.Web(MVP中的V) 立即下载

相关推荐

ASP.NET MVP模式实现(被动视图,依赖注入)

ASP.NET 的MVP模式简单实现,采用被动视图,Model层依赖注入实现,本来想用linq呢,但是方便移植起见,用了xml,别忘了自己修改配置文件的数据库地址

MVP模式基本用例开发

C# MVP模式基本用例开发 一、MVP 全称: Model-View-Presenter ;MVP 是从经典的模式MVC演变而来,它们的基本思想相似:Presenter负责逻辑的处理,Model提供数据源,View展现前台显示。 Presenter完全把Model和View进行了分离,主要的程序逻辑在Presenter里实现,避免View里面进行业务操作。Presenter与具体的View是没...

weixin_42725633的博客 657

从硬件拆解到图像生成:一次搞懂MRI设备(主磁体、梯度线圈、射频系统)是如何协同工作的

本文深入解析MRI设备的三大核心系统——主磁体、梯度线圈和射频系统如何协同工作,实现从量子现象到诊断图像的转化。通过详细的技术参数和临床案例,揭示磁共振成像(MRI)在医疗图像处理中的精密工程原理和最新技术突破,帮助读者全面理解这一现代医学影像技术的运作机制。

weixin_33734785的博客 554

ASP.NET 设计模式 MVP

前言 ASP.NET webform 使用后置代码页面隔离业务逻辑。但使用ASP.NET webform 做应用开发会存在以下不足: 后置代码页中混合了表现层、业务逻辑层、数据访问层的代码。出现这种情况的原因是后置代码负责事件触发,流程控制,业务规则和表现逻辑,业务逻辑和数据访问的协调者等多种角色。 后置代码页测试不方便。 Model-View-Presenter模式 Model...

weixin_30888707的博客 175

美团mtgsig 3.1.0算法还原:从加密入口到d1生成的完整链路拆解

本文详细拆解了美团mtgsig 3.1.0签名算法的完整逆向过程。通过定位加密入口函数eH,理清a6、a5、a8到d1的生成依赖链,并运用插桩技术,在JSVMP混淆环境下逐步还原了核心参数的生成逻辑,为逆向工程实践提供了清晰的纯算还原方法论。

oo7890的博客 785

CCSv3.3安装避坑全记录:从补丁失败到XDS510驱动,手把手搞定DSP开发环境

本文详细记录了CCSv3.3安装过程中的常见问题及解决方案,包括补丁安装失败、XDS510驱动识别异常等。通过系统环境准备、安装路径优化、补丁顺序调整等步骤,手把手帮助开发者搭建稳定的DSP开发环境,特别适合高校DSP实验课使用。

weixin_33494995的博客 329

MVP模式在asp.net中的应用

  前段时间,由于项目中需要用到MVP模式,于是我便来博客园查了一下,发现博客园有关MVP模式的资料少之又少,加上本人在博客园潜水这么久,也想出来透透气啦,从而产生了写博的冲动。整个项目做下来,也对MVP模式有了一定的了解,特写下这篇文章来做一个总结吧,希望对学习MVP模式的朋友有所帮助。话不多说,直接上图:        但是本章的重点不是这张图,而是在asp.net项目中怎么去用MVP模式...

weixin_30278237的博客 170

【DRAM存储器五十六】LPDDR5介绍--WCK2CK Leveling和Read gate training

简述LPDDR5 WCK2CK leveling和read gate traning基本原理与操作步骤

highman110的博客 8808

ASP.NET MVP( Model View Presenter )微软官方介绍

http://msdn.microsoft.com/en-us/magazine/cc188690.aspx

kasper99的专栏 1230

通过情感分类实例 详细介绍如果借助Huggingface平台 完成Transformers模型运行(包括配置环境-tokenizer-Model-输出头-预测)

attention_mask和padding是配套使用的,当人为去修改padding的时候,也要把attention_mask里面的参数进行修改。下载Huggingface包,Huggingface可以说是一个社区,集成了很多nlp的模型、数据集、预训练权重文件等等,并且免费,只需要pip install下载即可。那么用什么做分类就选择什么输出头,就import什么东西。代码中使用了自动分词器选择,它是由checkpoint指定的预训练模型关联的,不用我们自己选择tokenizer,它自动帮我们选择好了。

LZL2020LZL的博客 1140

Coze智能体实战:接口需求分析和接口调试

AI智能体的需求:能根据接口文档提取接口信息以及设计接口测试点,并进行接口调试返回接口测试结果。

十二测试录 284

使用ASP.NET实现Model View Presenter(MVP)

作者:Billy McCafferty 翻译:张善友 原文地址:http://www.codeproject.com/useritems/ModelViewPresenter.asp   这篇文章描述了ASP.NET 2.0使用Model-View-Presenter 模式实现业务逻辑与表现层的适当分离。 Download trivial example of MVP - 18 Kb ...

weixin_34314962的博客 164

Unreal从入门到精通之 UE4 vs UE5 VR性能优化实战

这篇文章分享了UE5 VR项目的性能优化经验。作者通过对比UE4和UE5的VR模板性能,发现UE5默认帧率只有45FPS,远低于UE4的100FPS。主要性能瓶颈来自Lumen全局光照、虚拟阴影贴图等新特性。文章详细列出了12项关键优化设置,包括禁用Lumen、关闭虚拟阴影、使用前向渲染等,并分析了各项调整对性能的影响程度。特别指出删除默认的VolumetricCloud可立即提升5帧。最后建议根据场景需求平衡画质与性能,对于高帧率要求的VR项目,可能需要谨慎使用UE5或关闭其部分高级渲染功能。

TxNet 1392

在ASP.NET中实现Model-View-Presenter(MVP) (转)

[原文地址]Implementing Model-View-Presenter in ASP.NET [原文作者]Alex Mueller [示例代码]下载示例代码 介绍 我在ASP.NET中使用MVP设计模式已经一年有余,在此之前我在一个使用事件驱动实现的SmartClient应用程序中第一次接触到了MVP模式,与富客户端环境相比,将MVP模式应用到Web环境仍然存在一些问题。...

weixin_30883311的博客 137

把 Custom Business Configurations 变成你的定制化维护台:Business Configuration Maintenance Object 设置全解

摘要:SAP BTP的Business Configuration(BCMO)为ABAP环境提供标准化的配置维护方案,通过RAP对象暴露为OData V4服务,自动生成Fiori elements维护界面,省去单独开发应用的成本。关键配置包括:Service Configuration定义业务名称和分组;List Report控制初始加载和视图变体;Object Page配置布局(Tabs/Page)和编辑权限;Table Settings选择表格类型(Grid/Responsive)和创建模式(Inlin

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 176

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

MVC、MVP以及Model2[下篇]

通过采用MVC模式,我们可以将可视化UI元素的呈现、UI处理逻辑和业务逻辑分别定义在View、Controller和Model中,但是对于三者之间的交互,MVC并没有进行严格的限制。最为典型的就是允许View和Model绕开Controller进行直接交互,View不仅仅可以通过调用Model获取需要呈现给用户的数据,Model也可以直接通知View让其感知到状态的变化。当真正地将MVC应用于具体

走在java的路途上 702

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

基于MVP架构设计ASP.Net的应用研究

微软的Microsoft patterns & practices小组, Web Client Software Factory采用是Mode View Presenter+Controller模式(MVPC模式),它可以使Model-View-Presenter 模式实现业务逻辑与表现层的适当分离,高效的简单的进行单元测试,更方便的隐藏技术的复杂度,方便的与各种系统集成等特点。以后

793

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

客户端框架-MVP

MVP Model-View-Presenter MVP是把MVC中的Controller换成了Presenter(呈现),目的就是为了完全切断View跟Model之间的联系,由Presenter充当桥梁,做到View-Model之间通信的完全隔离。 .NET程序员熟知的ASP.NET webform、winform基于事件驱动的开发技术就是使用的MVP模式。控件组成的页面充当View,...

dengjiyu8406的博客 213

设计模式学习:Model View Presenter (MVP)

设计模式学习:Model View Presenter (MVP) 经常看见圆子里有人谈论 mvp mvc 的相关技术知识,一直也没怎么练习 今天正好有人管我要一个demo 需求是这样的: 利用mvp模式做个 AS.NET 和 Windows Forms 都可以运行的Demo 抽空做了一下,也不知道我个人理解的是否正确、反正demo 已经做了 以我个人的理解,MVP主要就是要实现 界面...

weixin_34187862的博客 133
上一篇: ASP.NET下载文件出现提示框或者直接显示在浏览器中
下一篇: Jquery selector
eric0622
博客等级 码龄18年 1粉丝 9原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值