ASP.NET MVC Helpers, Merging two object htmlAttributes together

后端 未结 4 611
感情败类
感情败类 2021-02-01 03:46

I have a situation where I need to write an HTML Helper to extend another html helper. Normally, the helper would look like this.

@Html.TextAreaFo

4条回答
  •  星月不相逢
    2021-02-01 04:06

    First, create a method (the best would be to create an extension method) that converts an object to IDictionary via type reflection:

    public static IDictionary ToDictionary(this object data) 
    {
            if(data == null) return null; // Or throw an ArgumentNullException if you want
    
            BindingFlags publicAttributes = BindingFlags.Public | BindingFlags.Instance;
            Dictionary dictionary = new Dictionary();
    
            foreach (PropertyInfo property in 
                     data.GetType().GetProperties(publicAttributes)) { 
                if (property.CanRead) {
                    dictionary.Add(property.Name, property.GetValue(data, null));
                }
            }
            return dictionary;
    }
    

    Now, make use of C# 4.0 ExpandoObject, which allows adding properties at runtime. You would end up with something like this:

    public static MvcHtmlString CondensedHelperFor(this HtmlHelper htmlHelper, Expression> expression, object htmlAttributes) {
    {
        var dictAttributes = htmlAttributes.ToDictionary();
    
        var result = new ExpandoObject();
        var d = result as IDictionary; //work with the Expando as a Dictionary
    
        if(dictAttributes != null)
        {
            foreach (var pair in dictAttributes)
            {
                d[pair.Key] = pair.Value;
            }
        }
    
        // Add other properties to the dictionary d here
        // ...
    
        var stringBuilder = new System.Text.StringBuilder();
        var tag = new TagBuilder("div"); tag.AddCssClass("some_css");
        stringBuilder.Append(toolbar.ToString(TagRenderMode.SelfClosing));
        stringBuilder.Append(htmlHelper.TextAreaFor(expression, result));
    
        return new MvcHtmlString(stringBuilder.ToString());
    }
    

提交回复
热议问题