Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing Generics to Create HtmlHelper Extension Methods
    text
    copied!<p>I'm not really familiar with creating generic methods, so I thought I'd put this question to the community &amp; see what comes back. It might not even be a valid use of generics!</p> <p>I'd like to create a HtmlHelper extension method where I can specify that the method is of a certain type. I pass into the method an instance of that type, and an instance of a TagBuilder object. I then specify the class attribute of the tag to be the type of object I passed in, with all the object's properties serialized into the tag's attributes.</p> <p><strong>edit...</strong> the benefit of this would be that I could then easily serialize my Html elements in into javascript objects for jQuerying to the server &amp; Model Binding, as well as the ability to specify style for a type <strong>...end edit</strong></p> <p>This code sample might clarify.</p> <p>I have a type like this:</p> <pre><code>public class MyType { public int Prop1 { get; set; } public int Prop2 { get; set; } public MyType(int val1, int val2) { this.Prop1 = val1; this.Prop2 = val2; } } </code></pre> <p>What I'm thinking is to produce a helper method, maybe with a signature similar to this:</p> <pre><code>public static string GetTag&lt;T&gt;(this HtmlHelper h, object myType, TagBuilder tag) { // cast myType to T //(i.e. MyType) // use reflection to get the properties in MyType // get values corresponding to the properties // build up tag's attribute/value pairs with properties. } </code></pre> <p>Ideally I could then call:</p> <pre><code>&lt;% var myType = new MyType(123, 234); %&gt; &lt;% var tag = new TagBuilder("div"); %&gt; &lt;%= Html.GetTag&lt;MyType&gt;(myType, tag) %&gt; </code></pre> <p>and the html produced would be</p> <pre><code>&lt;div class="MyType" prop1="123" prop2="234" /&gt; </code></pre> <p>And later on, I can call</p> <pre><code>&lt;%= Html.GetTag&lt;MyOtherType&gt;(myOtherType, tag) %&gt; </code></pre> <p>to get</p> <pre><code>&lt;div class="MyOtherType" prop1="123" prop2="234" /&gt; </code></pre> <p>Is it even possible? Or am I looking at this totally the wrong way? Anyone care to fill me on on a better approach? </p> <p>Thanks</p> <p>Dave</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload