自己动手写控件(模仿mvc htmlhelper的类)

自定义helper类,要求命名空间在 System.Web.Mvc之下,要求,静态类,静态方法,特殊生成对应html的返回字段, 传递Htmlhleper,返回特定类型 返回值是MvcHtmlString ,参数要有:this HtmlHelper htmlHelper

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;


namespace System.Web.Mvc
{

/// <summary>
///要求,静态类,静态方法,特殊生成对应html的返回字段, 传递Htmlhleper,返回特定类型 返回值是MvcHtmlString ,
///
/// </summary>
public static class MyHtmlHelper
{
public static MvcHtmlString ListTextBox(this HtmlHelper htmlHelper, string[] data)
{
StringBuilder sb = new StringBuilder();
foreach(string s in data){

sb.Append(string.Format("<input id='{0}' name='{0}' style='' value='{0}'>{0}</input>", s));
}

return new MvcHtmlString(sb.ToString()) ;
}
}
}

页面:@CustomHtmlHelper.ListTextBox(this.Html,t) 这个就是使用自定义htmlhelper

@{
Layout = null;
}
@using System.Web.Mvc.Html
<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
@Html.CheckBox("te")
@{

string[] t=new string[2];
t[0] = "t1";
t[1] = "t2";
}
@CustomHtmlHelper.ListTextBox(this.Html,t)

</div>
</body>
</html>

原文地址:https://www.cnblogs.com/linbin524/p/4767168.html