自定义ViewHelper来简化Asp.net MVC view
日期:08-16  来源:
中国设计秀 作者:cnwebshow.com
让我们开始做到这一点,首先创建一个实现IViewObject接口的类,命名为HtmlFieldSet类并继承与AbstractHtmlViewObject,整个类的代码附下: zEJ中国设计秀
zEJ中国设计秀
public class HtmlFieldset : AbstractHtmlViewObject zEJ中国设计秀
{ zEJ中国设计秀
private readonly string mTitle; zEJ中国设计秀
zEJ中国设计秀
public HtmlFieldset( zEJ中国设计秀
ViewRequestContext requestContext, string name, zEJ中国设计秀
string title, object attributes) zEJ中国设计秀
: base(requestContext, name) zEJ中国设计秀
{ zEJ中国设计秀
mTitle = title; zEJ中国设计秀
Attributes = attributes; zEJ中国设计秀
} zEJ中国设计秀
zEJ中国设计秀
private TagBuilder FieldsetTag { get; set; } zEJ中国设计秀
zEJ中国设计秀
private TagBuilder OlTag { get; set; } zEJ中国设计秀
zEJ中国设计秀
public override void StartView() zEJ中国设计秀
{ zEJ中国设计秀
HttpResponseBase httpResponse = RequestContext.HttpResponse; zEJ中国设计秀
zEJ中国设计秀
FieldsetTag = new TagBuilder("fieldset"); zEJ中国设计秀
zEJ中国设计秀
// apply any Attributes passed in zEJ中国设计秀
if (Attributes != null) zEJ中国设计秀
{ zEJ中国设计秀
FieldsetTag.MergeAttributes(new RouteValueDictionary(Attributes)); zEJ中国设计秀
} zEJ中国设计秀
// The Name property should override any passed into the Attributes zEJ中国设计秀
FieldsetTag.MergeAttribute("name", Name, true); zEJ中国设计秀
zEJ中国设计秀
httpResponse.Write(FieldsetTag.ToString(TagRenderMode.StartTag)); zEJ中国设计秀
zEJ中国设计秀
if (!string.IsNullOrEmpty(mTitle)) zEJ中国设计秀
{ zEJ中国设计秀
TagBuilder legendTag = new TagBuilder("legend"); zEJ中国设计秀
legendTag.SetInnerText(mTitle); zEJ中国设计秀
httpResponse.Write(legendTag.ToString(TagRenderMode.Normal)); zEJ中国设计秀
} zEJ中国设计秀
zEJ中国设计秀
OlTag = new TagBuilder("ol"); zEJ中国设计秀
httpResponse.Write(OlTag.ToString(TagRenderMode.StartTag)); zEJ中国设计秀
} zEJ中国设计秀
zEJ中国设计秀
public override void EndView() zEJ中国设计秀
{ zEJ中国设计秀
HttpResponseBase httpResponse = RequestContext.HttpResponse; zEJ中国设计秀
zEJ中国设计秀
httpResponse.Write(OlTag.ToString(TagRenderMode.EndTag)); zEJ中国设计秀
httpResponse.Write(FieldsetTag.ToString(TagRenderMode.EndTag)); zEJ中国设计秀
} zEJ中国设计秀
} 这个类的实现和其它的view对象没什么不同,除了EndView方法,在这里我们需要EndView方法来生成必须的结束标记。当然我们也可以使用EndView来生成任何需要的HTML,在这里我们仅是用它生成结束标记。zEJ中国设计秀