eg3:扩展HtmlHelper
扩展方法类
1 public static class HtmlExtension 2 { 3 /// <summary> 4 /// 输出表单提交按钮 5 /// </summary> 6 /// <param name="htmlHelper">HtmlHelper对象</param> 7 /// <param name="name"></param> 8 /// <param name="value"></param> 9 /// <returns></returns> 10 public static MvcHtmlString Submit(this HtmlHelper htmlHelper,string name,string value) 11 { 12 //TagBuilder 用于辅助创建标记 13 var builder = new TagBuilder("input"); 14 builder.MergeAttribute("type","submit"); 15 //设置value属性 16 builder.MergeAttribute("value",value); 17 //设置name属性 18 builder.MergeAttribute("name",name); 19 //设置id属性 20 builder.GenerateId(name); 21 return MvcHtmlString.Create(builder.ToString()); 22 } 23 24 public static MvcHtmlString Submit(this HtmlHelper htmlHelper, string name, string value, object htmlAttributes) 25 { 26 //TagBuilder 用于辅助创建标记 27 var builder = new TagBuilder("input"); 28 builder.MergeAttribute("type", "submit"); 29 //设置value属性 30 builder.MergeAttribute("value", value); 31 //设置name属性 32 builder.MergeAttribute("name", name); 33 //设置id属性 34 builder.GenerateId(name); 35 //设置其他属性 36 builder.MergeAttributes(new RouteValueDictionary(htmlAttributes)); 37 return MvcHtmlString.Create(builder.ToString()); 38 } 39 }
//页面中进行使用
1 @{ 2 Layout = null; 3 } 4 @using ExtensionMethods.App_Code; 5 6 <!DOCTYPE html> 7 8 <html> 9 <head> 10 <meta name="viewport" content="width=device-width" /> 11 <title>Index</title> 12 </head> 13 <body> 14 <div> 15 @Html.Submit("login","登录") 16 17 @Html.Submit("login", "登录", new { @class="opt_sub",title="点击提交"}) 18 </div> 19 </body> 20 </html>