0

I have an HtmlHelper extension method that I am writing for an MVC/Razor website. The method signature is as follows:

public static IHtmlString CharacterCountOf<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper,
        Func<Expression<Func<TModel, TProperty>>, object, IHtmlString> helperMethod,
        Expression<Func<TModel, TProperty>> expression,
        object htmlAttributes){}

If you notice I am taking a method signature in as a parameter. These methods are typically going to be other HtmlHelper methods like TextAreaFor(). The object in the method signature are the html attributes. What I would like to do is take the anonymous type, add my own attribute to the object, and then call the method signature that was passed in as a parameter. Like so:

var identifier = Guid.NewGuid().ToString();
// somehow add identifier to htmlAttributes
helperMethod(expression, htmlAttributes)

All of the solutions that I have come across either change the htmlAttributes into an IDictionary which then won't work for the method signature or require you to know how the anonymous type was structured.

Here are some of the different approaches that I have tried/looked into: Use a Json object to construct an anonymous type, Use an extension method to map a dictionary to an anonymous type or convert the anonymous type to a dictionary, expandoObject, or dynamic

Since it was suggested here is why I am asking this question: This method is being used to generate the HTML/JS that counts the number of characters in a textbox/area and displays that count in the bottom right corner. I originally had all of the code in HTML/JS but while I was refactoring the existing text inputs I found that the number of steps needed to implement this functionality were annoying and fiddly. I could use C# to always include the annoying bits that make this work. With the new method refactoring and adding this feature to new text inputs becomes very easy.

Originally I tried firing the JS events on the name attribute which gets generated $([name='Description']).on('keyup') which worked great until I ran into a problem when there where more than one element with that attribute and value in the DOM. Therefore I needed a way to add a unique identifier to the HTML element that the JS would use to watch the text input.

Thomas927
  • 853
  • 1
  • 11
  • 19

0 Answers0