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
@pszmyd: You can use the ViewDataDictionary that already takes an object in the constructor ex.
//
// Summary:
// Initializes a new instance of the System.Web.Mvc.ViewDataDictionary class
// by using the specified model.
//
// Parameters:
// model:
// The model.
public ViewDataDictionary(object model);
Also what you are trying to do is simple enough - merging key values. In the case of html attributes it is not straight forward. ex. element can contain multiple classes ex. 'blue dr ltr', separated by spaces, while the style attribute uses the semi-colon as delimiter ex. 'width:200px; font-size:0.8em;'. It is really up to you to parse and check that the values are correct (not merging css classes instead of splitting them with spaces, same with the style).
I'd suggest from your parameter:object htmlAttributes
you just create: var htmlAttr = new ViewDataDictionary
then create custom extension methods to merge the attributes ex.
public static class ViewDataDictionaryExtensions
{
public static ViewDataDictionary MergeClasses(this ViewDataDictionary dict, string classes)
{
if (dict.ContainsKey("class"))
dict["class"] += " " + classes;
else
dict.Add("class", classes);
return dict;
}
public static ViewDataDictionary MergeStyles(this ViewDataDictionary dict, string styles)
{
if (dict.ContainsKey("style"))
dict["style"] += "; " + styles;
else
dict.Add("style", styles);
return dict;
}
}
This is only a really simple implementation not taking into account duplicate attribute values or multiple separators. But hope you get the idea!