首页 > 代码库 > MVC4 扩展方法

MVC4 扩展方法

1. 扩展代码机构

namespace System.Web.Mvc.Html{    public static class FormExtensions//表单相关扩展方法,例如创建表单标签等。    public static class InputExtensions//这里包含了所有input,例如:text,button,readiobutton等等。    public static class LinkExtensions//链接相关方法    public class MvcForm : IDisposable//与客户端控件无关    public static class RenderPartialExtensions//这是输出PartialView    public static class SelectExtensions//输出下拉框    public static class TextAreaExtensions//输出多行文本框    public static class ValidationExtensions//输出相关表单元素验证。}

 

2. TagBuilder 结构

    // Methods    public TagBuilder(string tagName);    public void AddCssClass(string value);//增加样式    public void GenerateId(string name);//设置控件ID    private string GetAttributesString();    public void MergeAttribute(string key, string value);//设置属性值    public void MergeAttribute(string key, string value, bool replaceExisting);    public void MergeAttributes<TKey, TValue>(IDictionary<TKey, TValue> attributes);    public void MergeAttributes<TKey, TValue>(IDictionary<TKey, TValue> attributes, bool replaceExisting);    public void SetInnerText(string innerText);//设置显示文本    public override string ToString();    public string ToString(TagRenderMode renderMode);//输出控件html

 

3. 示例: Html.Image(...)

public static class ImageHelper{        public static string Image(this HtmlHelper helper, string id, string url, string alternateText)        {            return Image(helper, id, url, alternateText, null);        }        public static string Image(this HtmlHelper helper, string id, string url, string alternateText, object htmlAttributes)        {            // 创建IMG标签            var builder = new TagBuilder("img");            // 增加ID属性            builder.GenerateId(id);            // 增加属性            builder.MergeAttribute("src", url);            builder.MergeAttribute("alt", alternateText);            builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));            // 输出完整的img标签            return builder.ToString(TagRenderMode.SelfClosing);        }}