淺談ASP.NET MVC的MvcContrib.FluentHtml
我們力求頁面層代碼簡潔并具有較好的可讀性,在ASP.NET MVC的平臺上,我們以新的起點來實現(xiàn)這一目標.MvcContrib.FluentHtml和Spark ViewEngine給我們做出了榜樣.本文將以MvcContrib.FluentHtml為例探究它的實現(xiàn)機制:Fluent Interface.
ASP.NET MVC
在MvcContrib.FluentHtml的應(yīng)用中,我們隨處可以見到下面的代碼:
- <%=this.TextBox(x=>x.Person.Name).Title("Entertheperson'sname").Label("Name:")%><br/>
- ……
- <%=this.Select(x=>x.Person.Gender).Options(Model.Genders).Size(5).Label("Gender:")
- .Title("Selecttheperson'sgender")%><br/>
- <labelidlabelid="Person_Name_Label"for="Person_Name">Name:</label>
- <inputidinputid="Person_Name"type="text"value="Jeremy"title="Entertheperson'sname"name="Person.Name"maxlength="50"/>
- .
- <selectidselectid="Person_Gender"title="Selecttheperson'sgender"size="5"name="Person.Gender">
- <optionvalueoptionvalue="M"selected="selected">Male</option>
- <optionvalueoptionvalue="F">Female</option>
- </select>
這種實現(xiàn)編程方式就是"Fluent Interface",這并不是什么新概念,2005年Eric Evans 和Martin Fowler就為這種實現(xiàn)方式命名.源文檔 <http://www.martinfowler.com/bliki/FluentInterface.html> 可以通過維基百科中對Fluent Interface的描述獲得一個基本的了解:In software engineering, a fluent interface (as first coined by Eric Evans and Martin Fowler) is a way of implementing an object oriented API in a way that aims to provide for more readable code.
我們分解上面的話:
◆它是面向?qū)ο驛PI的一種實現(xiàn)方式
◆目的是增加代碼的可讀性
既然我們最熟悉的是StringBuilder,我們就從這個線索追下去:打開Reflector,很容易找到StringBuilder的Append方法:
- publicStringBuilderAppend(stringvalue)
- {
- if(value!=null)
- {
- stringstringValue=this.m_StringValue;
- IntPtrcurrentThread=Thread.InternalGetCurrentThread();
- if(this.m_currentThread!=currentThread)
- {
- stringstringValue=string.GetStringForStringBuilder(stringValue,stringValue.Capacity);
- }
- intlength=stringValue.Length;
- intrequiredLength=length+value.Length;
- if(this.NeedsAllocation(stringValue,requiredLength))
- {
- stringnewString=this.GetNewString(stringValue,requiredLength);
- newString.AppendInPlace(value,length);
- this.ReplaceString(currentThread,newString);
- }
- else
- {
- stringValue.AppendInPlace(value,length);
- this.ReplaceString(currentThread,stringValue);
- }
- }
- returnthis;
- }
了解了Fluent Interface,我們來看一下MVCContrib.FluentHTML的實現(xiàn),這里以TextBox為例進行考察,首先看一下它的繼承關(guān)系:
public class TextBox : TextInput< TextBox>
public abstract class TextInput< T> : Input< T>, ISupportsMaxLength where T : TextInput< T>
public abstract class Input< T> : FormElement< T> where T : Input< T>, Ielement
泛型是一種高層次的算法抽象,我們就通過Input< T>一窺端倪:
- publicabstractclassInput<T>:FormElement<T>whereT:Input<T>,IElement
- {
- protectedobjectelementValue;
- protectedInput(stringtype,stringname):base(HtmlTag.Input,name)
- {
- builder.MergeAttribute(HtmlAttribute.Type,type,true);
- }
- protectedInput(stringtype,stringname,MemberExpressionforMember,
IEnumerable<IBehaviorMarker>behaviors)- :base(HtmlTag.Input,name,forMember,behaviors)
- {
- builder.MergeAttribute(HtmlAttribute.Type,type,true);
- }
- ///<summary>
- ///Setthe'value'attribute.
- ///</summary>
- ///<paramnameparamname="value">Thevaluefortheattribute.</param>
- publicvirtualTValue(objectvalue)
- {
- elementValue=value;
- return(T)this;
- }
- ///<summary>
- ///Setthe'size'attribute.
- ///</summary>
- ///<paramnameparamname="value">Thevaluefortheattribute.</param>
- publicvirtualTSize(intvalue)
- {
- Attr(HtmlAttribute.Size,value);
- return(T)this;
- }
- protectedoverridevoidPreRender()
- {
- Attr(HtmlAttribute.Value,elementValue);
- base.PreRender();
- }
- }
總結(jié)
為了能夠在View中能夠簡潔清晰的構(gòu)造HTML元素,ASP.NET MVC中通過htmlHelper.InputHelper來實現(xiàn)頁面元素的構(gòu)造. 頁面層所使用的<%= Html.TextBox("username") %>,HTML也是htmlHelper的Extension Method.相比較起來,htmlHelper提供了基礎(chǔ)的頁面控件定義和構(gòu)造,而FluentHTML表現(xiàn)的更為靈活.除了FluentHTML,著名的Spark View Engine也有類似的實現(xiàn),大家可以關(guān)注一下.
【編輯推薦】