当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET MVC HtmlHelper如何扩展

ASP.NET MVC HtmlHelper如何扩展

2017年12月12日  | 移动技术网IT编程  | 我要评论

一、asp.net 扩展方法三要素

(1)、静态类

可以从下图看出,inputextension首先是一个静态类;

(2)、静态方法

既然是静态类,那么其所有的方法必然都是静态方法,例如:public static mvchtmlstring checkbox();

(3)、this关键字

可以从方法名定义中看出,第一个参数都是this htmlhelper htmlhelper,代表对htmlhelper类的扩展;

二、通过 mvc  htmlhelper扩展 实例简单说明扩展步骤

实例1、扩展submit

using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.web.mvc;
namespace testmvchelper
{
  public static class htmlextensions
  {
    public static mvchtmlstring submit(this htmlhelper helper, string value)
    {
      var builder = new tagbuilder("input"); //使我们创建的标签名字设为input
      builder.mergeattribute("type", "submit"); //添加属性 type="submit"
      builder.mergeattribute("value", value);
      return mvchtmlstring.create(builder.tostring(tagrendermode.selfclosing)); 
    }
  }
}

上述实例说明

(1)、在使用tagbuilder需要引入命名空间system.web.mvc。
(2)、submit方法名是对应视图中调用的名称。 (如:@html.submit("提交") )
(3)、this htmlhelper

helper 将submit方法添加到htmlhelper中,value是传过来的提交按钮上的文字。
(4)、var builder = new tagbuilder("input");     

设置标签名字设为input。
(5)、builder.mergeattribute("type", "submit")  

设置标签属性type="submit"。
(6)、builder.mergeattribute("value", value);     

设置标签提交按钮value值。
(7)、tagrendermode.selfclosing                    

表示用于呈现自结束标记(例如,<input />)的模式。
(8)、tagrendermode是个枚举类,分别为

normal(表示用于呈现正常文本的模式)

starttag(表示用于呈现开始标记(例如,<tag>)的模式)

endtag(表示用于呈现结束标记(例如,</tag>)的模式)

selfclosing(表示用于呈现自结束标记(例如,<tag />)的模式)。
(9)、mvchtmlstring作为返回值是为了使返回值不被转义,比如"<"不会被转成"<"。

view中调用

@html.submit("提交")

实例2、扩展超链接

http://www.codehighlighter.com/--> 1 /// <summary>
/// 带描述的链接扩展方法
/// </summary>
/// <param name="htmlhelper">要扩展的htmlhelper类</param>
/// <param name="title">标题</param>
/// <param name="url">链接地址</param>
/// <param name="description">描述</param>
/// <returns>html代码</returns>
public static mvchtmlstring linkwithdescription(this htmlhelper htmlhelper, string title, string url, string description)
{
  // 生成与标题链接有关的html代码
  tagbuilder titlecontainer = new tagbuilder("p");  // 标题链接容器p
  tagbuilder titlelink = new tagbuilder("a");  // 标题中的文字要有链接,所以包含在a标签内
  titlelink.mergeattribute("href", url);  // 为a添加href属性并指定链接地址
  titlelink.setinnertext(title);  // 标题文字
  titlecontainer.innerhtml = titlelink.tostring();  // 将a放到p中
  titlecontainer.addcssclass("linktitle");  // 为标题添加样式

  // 生成与链接描述有关的html代码
  tagbuilder descriptioncontainer = new tagbuilder("p");  // 连接描述容器p
  descriptioncontainer.innerhtml = description;  // 描述文字
  descriptioncontainer.addcssclass("linkdescription");  // 为描述添加样式

  // 将上述元素放入一个div中
  tagbuilder div = new tagbuilder("div");
  div.innerhtml = string.format("{0}{1}", titlecontainer.tostring(), descriptioncontainer.tostring());

  // 返回生成的html代码
  return mvchtmlstring.create(div.tostring());
}

视图中调用

@html.linkwithdescription("测试链接1""#""这是测试链接1的描述")

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网