ASP.NET MVC控件项目开发的简单分析
创始人
2024-06-06 13:40:44
0

【51CTO编者按】对于ASP.NET MVC框架大家一定不会陌生,但是对于很多人来说,弄好一个ASP.NET MVC控件项目实在是费劲的事情。这里由作者来介绍他的一个ASP.NET MVC控件项目经历。51CTO编辑推荐《ASP.NET MVC框架视频教程

在写本文之前,本人一直抱着‘不宜’在ASP.NET MVC框架下搞什么控件开发的想法,因为一提到控件就会让人想起‘事件’,‘VIEWSTATE’等一些问题,而ASP.NET MVC下是Controller, Action, Viewpage, Filter等特性的‘天下’。所以总感觉‘驴唇对不上马嘴’。

但直到前阵子在邮箱中收到了关于telerik关于MVC框架扩展的一些信息之后,才发现这家商业控件公司也开始打MVC的主意了。而这个项目(开源)就是该公司在理解了asp.net mvc的基础上所做的一些尝试,当然其所实现的所谓控件与之前我们在项目中所开发或使用的web服务器控件有很大的不同,可以说是抛弃了以往的设计方式。尽管目前它的这种做法我心里还打着问号,但必定是一种尝试(不管你赞同还是不赞同)。下面就做一个简单的分析,希望能给研究MVC架构的朋友提供一些的思考。

首先要声明的是该开源项目中所使用的js就是jquery,而那些显示效果也基本上就是基于jQuery中的那件插件为原型,并进行相应的属性封装,以便于在viewpage中用C#等语言进行声明绑定。下面就其中一些控件的显示截图:

控件的显示截图

控件显示截图

ASP.NET

进度条控件

在该开源项目中,所有控件均基于jQueryViewComponentBase (abstract 类型),但其自身属性并不多,而所有的控件基类属性都被jQueryViewComponentBase 的父类ViewComponentBase所定义,下面以控件中的“Accordion(属性页控件)”为例进行说明,见下图:

Accordion(属性页控件)

上图中左侧的就是ViewComponentBase类,其定义了多数控件属性,比如js脚本名称和路径以及相关样式以及最终的html元素输出方法,因为其类也是抽象类,所以其中大部分方法均为定义,而未进行具体实现。我们只要关注一下其构造方法就可以了:

  1. ///  
  2. /// View component base class.  
  3. /// 
  4.  
  5.     public abstract class ViewComponentBase : IStyleableComponent, IScriptableComponent  
  6. {  
  7. private string name;  
  8. private string styleSheetFilesLocation;  
  9. private string scriptFilesLocation;  
  10. ///  
  11. /// 初始化相关Initializes a new instance of the  cref="ViewComponentBase"/> class.  
  12. /// 
  13.  
  14. ///  name="viewContext">当前视图的上下文,将会在子类中使用 
  15. ///  name="clientSideObjectWriterFactory">传入当前所使用的Writer工厂实例.通过子类注入,子类最终延伸到相对应的控件实例 
  16.         protected ViewComponentBase(ViewContext viewContext, IClientSideObjectWriterFactory clientSideObjectWriterFactory)  
  17. {  
  18. Guard.IsNotNull(viewContext, "viewContext");  
  19. Guard.IsNotNull(clientSideObjectWriterFactory, "clientSideObjectWriterFactory");  
  20. ViewContext = viewContext;  
  21. ClientSideObjectWriterFactory = clientSideObjectWriterFactory;  
  22. StyleSheetFilesPath = WebAssetDefaultSettings.StyleSheetFilesPath;  
  23. StyleSheetFileNames = new List();  
  24. ScriptFilesPath = WebAssetDefaultSettings.ScriptFilesPath;  
  25. ScriptFileNames = new List();  
  26. HtmlAttributes = new RouteValueDictionary();  
  27. }  

通过上述的构造方法,就可以将控件的一些通用默认属性值进行初始化了。

下面以“Accordion”的源码来分析一下,这里还是从构造方法入手:

  1. public class Accordion : jQueryViewComponentBase, IAccordionItemContainer  
  2. {  
  3. ……  
  4. ///  
  5. /// Initializes a new instance of the  cref="Accordion"/> class.  
  6. /// 
  7.  
  8. ///  name="viewContext">The view context. 
  9. ///  name="clientSideObjectWriterFactory">The client side object writer factory. 
  10.        public Accordion(ViewContext viewContext, IClientSideObjectWriterFactory clientSideObjectWriterFactory) : base(viewContext, clientSideObjectWriterFactory)  
  11. {  
  12. Items = new List();  
  13. autoHeight = true;  
  14. }  

注:上面的构程方法后面加入了base(viewContext, clientSideObjectWriterFactory),以实现向基类构造方法传参,也就是实现了上面所说的将当前控件所使用的viewContext,clientSideObjectWriterFactory传递到基类ViewComponentBase 中去。(注:最终的clientSideObjectWriterFactory为ClientSideObjectWriterFactory实例类型)。

当然,因为该控件的中相应属性比较简单,只是一些set,get语法,所以就不过多介绍了,相信做过控件开发的对这些再熟悉不过了。

下面主要介绍一下其write html元素时所使用的方法,如下:

 

  1. ///  
  2. /// 创建并写入初始化脚本对象和相应属性.  
  3. /// 
  4.  
  5. ///  name="writer">The writer. 
  6.       public override void WriteInitializationScript(TextWriter writer)  
  7. {  
  8. int selectedIndex = Items.IndexOf(GetSelectedItem());  
  9. IClientSideObjectWriter objectWriter = ClientSideObjectWriterFactory.Create(Id, "accordion", writer);  
  10. objectWriter.Start()  
  11. .Append("active", selectedIndex, 0)  
  12. .Append("animated", AnimationName)  
  13. .Append("autoHeight", AutoHeight, true)  
  14. .Append("clearStyle", ClearStyle, false)  
  15. .Append("collapsible", CollapsibleContent, false)  
  16. .Append("event", OpenOn)  
  17. .Append("fillSpace", FillSpace, false);  
  18. if (!string.IsNullOrEmpty(Icon) || !string.IsNullOrEmpty(SelectedIcon))  
  19. {  
  20. if (!string.IsNullOrEmpty(Icon) && !string.IsNullOrEmpty(SelectedIcon))  
  21. {  
  22. objectWriter.Append("icons:{'header':'" + Icon + "','headerSelected':'" + SelectedIcon + "'}");  
  23. }  
  24. else if (!string.IsNullOrEmpty(Icon))  
  25. {  
  26. objectWriter.Append("icons:{'header':'" + Icon + "'}");  
  27. }  
  28. else if (!string.IsNullOrEmpty(SelectedIcon))  
  29. {  
  30. objectWriter.Append("icons:{'headerSelected':'" + SelectedIcon + "'}");  
  31. }  
  32. }  
  33. objectWriter.Append("change", OnChange).Complete();  
  34. base.WriteInitializationScript(writer);  
  35. }  

可以看出,objectWriter (IClientSideObjectWriter 类型实例)中被绑定了相关的控件属性,并通过其类的WriteInitializationScript(writer)进行脚本的输出。而基本类的相应方法如下:    

  1.  ///  
  2. /// Writes the initialization script.  
  3. /// 
  4.  
  5. ///  name="writer">The writer. 
  6.       public virtual void WriteInitializationScript(TextWriter writer)  
  7. {  
  8. }  

大家看到该方法为空,但其又是如何运行起来的呢,这里先卖个关子,稍后再说。接着再看一下另一个方法:WriteHtml()

  1. ///  
  2. /// 输出当前的 HTML代码.  
  3. /// 
  4.  
  5.       protected override void WriteHtml()  
  6. {  
  7. AccordionItem selectedItem = GetSelectedItem();  
  8. TextWriter writer = ViewContext.HttpContext.Response.Output;  
  9. if (!string.IsNullOrEmpty(Theme))  
  10. {  
  11. writer.Write(" class=\"{0}\">".FormatWith(Theme));  
  12. }  
  13. HtmlAttributes.Merge("id", Id, false);  
  14. HtmlAttributes.AppendInValue("class", " ", "ui-accordion ui-widget ui-helper-reset");  
  15. writer.Write("{0}>".FormatWith(HtmlAttributes.ToAttributeString()));  
  16. foreach (AccordionItem item in Items)  
  17. {  
  18. item.HtmlAttributes.AppendInValue("class", " ", "ui-accordion-header ui-helper-reset ui-state-default ");  
  19. item.ContentHtmlAttributes.AppendInValue("class", " ", "ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom");  
  20. if (item == selectedItem)  
  21. {  
  22. item.ContentHtmlAttributes.AppendInValue("class", " ", "ui-accordion-content-active");  
  23. }  
  24. else  
  25. {  
  26. item.HtmlAttributes.AppendInValue("class", " ", "ui-corner-all");  
  27. }  
  28. writer.Write("{0}> href=\"#\">{1}".FormatWith(item.HtmlAttributes.ToAttributeString(), item.Text));  
  29. item.ContentHtmlAttributes.AppendInValue("style", ";", (item == selectedItem) ? "display:block" : "display:none");  
  30. writer.Write("{0}>".FormatWith(item.ContentHtmlAttributes.ToAttributeString()));  
  31. item.Content();  
  32. writer.Write("
");  
  • }  
  • writer.Write("
  • ");  
  • if (!string.IsNullOrEmpty(Theme))  
  • {  
  • writer.Write("
  • ");  
  • }  
  • base.WriteHtml();  
  • }  
  • 该方法首先获取当前所选属性页标签(GetSelectedItem()方法),然后用foreach方法对属性页标签集合进行遍历,并判断当前属性页是否就是被选中的属性页,并绑定上相应的css属性。其最终也是调用相应的基类方法进行输出。当然这里基类方法也是为空,呵呵。

    准备好了这个控件类之后,Telerik还为Accordion控件‘准备’了一些辅助组件,比如属性页组件(AccordionItem),以及相关的组件构造器(AccordionItemBuilder,AccordionBuilder),这样我们就可以通过这些构造器很方便的创建相应的控件和组件了,下面就以AccordionItemBuilder为例,解释一下其构造器结构:

    1. public class AccordionBuilder : ViewComponentBuilderBase, AccordionBuilder>, IHideObjectMembers  
    2. {  
    3. ///  
    4. /// 初始化方法Initializes a new instance of the  cref="AccordionBuilder"/> class.  
    5. /// 
    6.  
    7. ///  name="component">The component. 
    8.       public AccordionBuilder(Accordion component) : base(component)  
    9. {}  
    10. ///  
    11. /// 指定一个属性页选项  
    12. /// 
    13.  
    14. ///  name="addAction">要添加的action. 
    15. ///  
    16.       public virtual AccordionBuilder Items(Action addAction)  
    17. {  
    18. Guard.IsNotNull(addAction, "addAction");  
    19. AccordionItemFactory factory = new AccordionItemFactory(Component);  
    20. addAction(factory);  
    21. return this;  
    22. }  
    23. ///  
    24. /// 属性页动态效果显示名称(鼠标在属性页移入移出时)  
    25. /// 
    26.  
    27. ///  name="effectName">Name of the effect. 
    28. ///  
    29.       public virtual AccordionBuilder Animate(string effectName)  
    30. {  
    31. Component.AnimationName = effectName;  
    32. return this;  
    33. }  
    34. ///  
    35. /// 是否高度自适用.  
    36. /// 
    37.  
    38. ///  name="value">if set to true value. 
    39. ///  
    40.       public virtual AccordionBuilder AutoHeight(bool value)  
    41. {  
    42. Component.AutoHeight = value;  
    43. return this;  
    44. }  
    45.  
    46. ///  
    47. /// 指定要触发的属性页事件名称.  
    48. /// 
    49.  
    50. ///  name="eventName">Name of the event. 
    51. ///  
    52.       public virtual AccordionBuilder OpenOn(string eventName)  
    53. {  
    54. Component.OpenOn = eventName;  
    55. return this;  
    56. }  
    57. ///  
    58. /// 所使用的Icons名称.  
    59. /// 
    60.  
    61. ///  name="name">The name. 
    62. ///  
    63.       public virtual AccordionBuilder Icon(string name)  
    64. {  
    65. Component.Icon = name;  
    66. return this;  
    67. }  
    68. ///  
    69. /// 被选中的属性页所使用的Icons 名称  
    70. /// 
    71.  
    72. ///  name="name">The name. 
    73. ///  
    74.       public virtual AccordionBuilder SelectedIcon(string name)  
    75. {  
    76. Component.SelectedIcon = name;  
    77. return this;  
    78. }  
    79. ///  
    80. /// 当属性页发生变化时要传递的action 脚本.  
    81. /// 
    82.  
    83. ///  name="javaScript">The java script. 
    84. ///  
    85.       public virtual AccordionBuilder OnChange(Action javaScript)  
    86. {  
    87. Component.OnChange = javaScript;  
    88. return this;  
    89. }  
    90. ///  
    91. /// Specify the name of the theme applies to the accordion.  
    92. /// 
    93.  
    94. ///  name="name">The name. 
    95. ///  
    96.       public virtual AccordionBuilder Theme(string name)  
    97. {  
    98. Component.Theme = name;  
    99. return this;  
    100. }  
    101. }  

    对于上面的OnChange方法,可以使用下面的方法将相应的js脚本传入并执行

    1. .OnChange(() => 
    2. {%> 
    3. function(event, ui)  
    4. {  
    5. $('#trace').append('Change fired: ' + new Date() + '
      ');  
    6. }  
    7. <%}  
    8. )  

    这样,当属性页发生变化时,就会在页面的指定区域将变化时间显示出来了,如下图:

    属性页发生变化

    Telerik在jQueryViewComponentFactory中对项目中每一个控件提供了一个方法用以初始化相应的构造器,以便于创建相应的控件,比如Accordion,形如: 

    1.  ///  
    2. /// Creates a accordion for ASP.NET MVC view.  
    3. /// 
    4.  
    5. ///  
    6.      [DebuggerStepThrough]  
    7. public virtual AccordionBuilder Accordion()  
    8. {  
    9. return new AccordionBuilder(Create(() => new Accordion(ViewContext, clientSideObjectWriterFactory)));  
    10. }  

    而对于其在VIEW中的使用,则通过扩展方法来加以声明:

    1. public static class HtmlHelperExtension  
    2. {  
    3. private static readonly IClientSideObjectWriterFactory factory = new ClientSideObjectWriterFactory();  
    4. ///  
    5. /// Gets the jQuery view components instance.  
    6. /// 
    7.  
    8. ///  name="helper">The html helper. 
    9. /// jQueryViewComponentFactory 
    10.        [DebuggerStepThrough]  
    11. public static jQueryViewComponentFactory jQuery(this HtmlHelper helper)  
    12. {  
    13. return new jQueryViewComponentFactory(helper, factory);  
    14. }  
    15. }  

    这样在页面视图中,我们这可以使用下面的写法来构造一个Accordion控件了:

    1. <% Html.jQuery().Accordion()  
    2. .Name("myAccordion")  
    3. .Animate("bounceslide")  
    4. .Items(parent => 
    5. ……  

    上面只是介绍了前台和底层代码如果显示的问题,但还没有解释之前所说的WriteInitializationScript(TextWriter writer)方法以及WriteHtml()
    方法如何被调用的问题,正如之前所看到的,因为Accordion的基类ViewComponentBase中未实现具体的代码,所以这里我们要将注意力转移到 jQueryViewComponentFactory中,请看如下代码: 

    1. private TViewComponent Create(Func factory) where TViewComponent : ViewComponentBase  
    2. {  
    3. TViewComponent component = factory();  
    4. if (component is jQueryViewComponentBase)  
    5. {  
    6. component.AssetKey = DefaultAssetKey;  
    7. }  
    8. htmlHelper.Telerik().StyleSheetRegistrar().ToRegistrar().Register(component);  
    9. htmlHelper.Telerik().ScriptRegistrar().ToRegistrar().Register(component);  
    10. return component;  
    11. }  

    上面的方法其实就是之前在该类方法Accordion()中所调用并执行的:

    1. return new AccordionBuilder(Create(() => new Accordion(ViewContext, clientSideObjectWriterFactory))); 
    通过该方法,就可以将该控件及其相关组件信息注册到相应的视图中。因为我们比较关注WriteHtml()方法,所以这里就直接分析一下这一行代码:      ScriptRegistrar().ToRegistrar().Register(component); ScriptRegistrar类中的Register方法承担着将当前要创建的组件添加到当前的脚本组件列表中的任务(scriptableComponents为list列表)    
    1.  
    2.        ///  
    3. /// Registers the scriptable component.  
    4. /// 
    5.  
    6. ///  name="component">The component. 
    7.        public virtual void Register(IScriptableComponent component)  
    8. {  
    9. Guard.IsNotNull(component, "component");  
    10. if (!scriptableComponents.Contains(component))  
    11. {  
    12. scriptableComponents.Add(component);  
    13. }  
    14. }  

    当组件被成功添加到该list列表中后,系统就会调用Render()方法将其显示出来(注:该方法与以前web控件开发中的显示方法同名,所以比较好理解),如下:   

    1.     ///  
    2. /// Writes the scripts in the response.  
    3. /// 
    4.  
    5.       public void Render()  
    6. {  
    7. if (hasRendered)  
    8. {  
    9. throw new InvalidOperationException(Resources.TextResource.YouCannotCallRenderMoreThanOnce);  
    10. }  
    11. if (ViewContext.HttpContext.Request.Browser.EcmaScriptVersion.Major >= 1)  
    12. {  
    13. Write(ViewContext.HttpContext.Response.Output);  
    14. }  
    15. hasRendered = true;  
    16. }  

    注意上面的这一行代码:

    Write(ViewContext.HttpContext.Response.Output);

    其所实现的功能如下:  

    1.     ///  
    2. /// 写出所有脚本资源和脚本 statements.  
    3. /// 
    4.  
    5. ///  name="writer">The writer. 
    6.       protected virtual void Write(TextWriter writer)  
    7. {  
    8. WriteScriptSources(writer);  
    9. WriteScriptStatements(writer);  
    10. }  

    而就是WriteScriptStatements这行代码开始执行之前所说的那个WriteInitializationScript(TextWriter writer)。而WriteHtml()方法的执行入口要更加复杂一些,因为Telerik提供了ViewComponentBuilderBase这个类来进行视图组件的构造,而该类中的Render方法就是对相应组件的Render方法(组件中已定义)进行调用,如下:

    1.     ///  
    2. /// Renders the component.  
    3. /// 
    4.  
    5.     public virtual void Render()  
    6. {  
    7. Component.Render();  
    8. }  

    而之前的“Accordion”控件是继承自ViewComponentBase类,所以相应组件的Render方法就在该类中进行了声明定义,如下:

    1.   ///  
    2. /// Renders the component.  
    3. /// 
    4.  
    5.      public void Render()  
    6. {  
    7. EnsureRequired();  
    8. WriteHtml();  
    9. }  

    大家看到了第二行代码了吧,这就是我们之前看到的那个方法,也就是Accordion组件中WriteHtml()重写方法的调用入口。

    绕了这么一大圈,才把这个流程理清,是不是有些晕了。的确,刚开始接触时我也有点晕,但晕呀晕呀就‘晕过去了’,现在再回头看起来感常见其整体的架构思路还是很清晰的。可以说有了这瓶酒垫底,再分析该项目中的其它控件就‘如鱼得水’了。

    ***不妨总结一下:

    这是对ASP.NET MVC控件项目开发做的一次尝试,但如果之前做过控件特别是web服务器端控件开发的朋友,可以看出项目中有非常重的web控件开发味道,基本连方法名称都有一定的重叠。

    另外就是其自身还是引用了组件对象模型的概念,就拿属性页控件来说,就将其分为Accordion和AccordionItem两种类型,其中可以将Accordion看成是AccordionItem的集合封装(包括遍历操作),而这里AccordionItem就成了Accordion的一个组件,而Accordion又是当前view中的一个组件。而组件开发一直是.NET平台上所倡导的。其优势在于可复用,维护方便,简化复杂问题等。

    原文标题:一个Asp.net MVC 控件项目分析---Telerik.Web.Mvc

    链接:http://www.cnblogs.com/daizhj/archive/2009/09/09/1562966.html

    【编辑推荐】

    1. 点评一下ASP.NET的WEB控件
    2. ASP.NET控件学习总结
    3. ASP.NET前台控件点评:避免强迫症,奔向简洁高效
    4. ASP.NET 2.0环境下的Shell函数
    5. 在ASP.NET 2.0中向数据库批量插入数据

    相关内容

    热门资讯

    如何允许远程连接到MySQL数... [[277004]]【51CTO.com快译】默认情况下,MySQL服务器仅侦听来自localhos...
    如何利用交换机和端口设置来管理... 在网络管理中,总是有些人让管理员头疼。下面我们就将介绍一下一个网管员利用交换机以及端口设置等来进行D...
    施耐德电气数据中心整体解决方案... 近日,全球能效管理专家施耐德电气正式启动大型体验活动“能效中国行——2012卡车巡展”,作为该活动的...
    Windows恶意软件20年“... 在Windows的早期年代,病毒游走于系统之间,偶尔删除文件(但被删除的文件几乎都是可恢复的),并弹...
    20个非常棒的扁平设计免费资源 Apple设备的平面图标PSD免费平板UI 平板UI套件24平图标Freen平板UI套件PSD径向平...
    德国电信门户网站可实时显示全球... 德国电信周三推出一个门户网站,直观地实时提供其安装在全球各地的传感器网络检测到的网络攻击状况。该网站...
    着眼MAC地址,解救无法享受D... 在安装了DHCP服务器的局域网环境中,每一台工作站在上网之前,都要先从DHCP服务器那里享受到地址动...
    为啥国人偏爱 Mybatis,... 关于 SQL 和 ORM 的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行...