1

I'm wondering about preparing generic partial view (or HTML helper) which could generate the table based on view model members and its metadata.

It should look similar to this: C# reflection use variable as object.[var]

Is it a good idea or I should forget about it and every time write the code manually because reflection would be too slow?

Are there any tools / add-ons which are able to generate such a code from a view model?

Community
  • 1
  • 1
Arkadiusz Kałkus
  • 17,101
  • 19
  • 69
  • 108
  • 3
    You might be interested in [this article](http://www.codeproject.com/Articles/774228/MVC-Html-Table-Helper-Part-Display-Tables) –  Mar 30 '15 at 07:33
  • Reflection isn't as expensive as you think - and ASP.NET MVC (and especially the `FooFor( m => m.Foo )` HTML Helpers) are based on reflection. Provided you cache the reflection objects you'll be fine - only watch out if you're running a tight-loop, which web-applications rarely do. – Dai Mar 30 '15 at 07:41
  • @StephenMuecke Thank you very much! It's highly inspiring implementation of the idea I had! – Arkadiusz Kałkus Mar 31 '15 at 11:46
  • @Dai Thank you. i didn't know that HTML for helpers are based on the reflection. Could you tell me how you figured it out? Is it somewhere explained or you dig into MVC source code? (Quick google query didn't give me any result about it) – Arkadiusz Kałkus Apr 01 '15 at 07:02

1 Answers1

6

There's nothing wrong (per se) with using reflection in your views and I seriously doubt you'd notice any performance issues with it; however, I would always recommend trying to encapsulate the behavior in an HTML helper if possible as there are certain benefits you'll gain from doing it that you otherwise wouldn't, these are:

  • Increased re-usability,
  • Easier to unit test
  • Benefit of compile time checking
Joseph Woodward
  • 9,191
  • 5
  • 44
  • 63
  • Thank you, Joe. Tip of creating MVC helpers is useful, Stephen Muecke's comment has helped me a lot also in this matter. – Arkadiusz Kałkus Apr 01 '15 at 07:00
  • 1
    It's not a problem, I'm glad I could help! Another really powerful way of creating re-usable view components [is this question](http://stackoverflow.com/questions/23518499/creating-reusable-html-view-components-using-razor-in-asp-net-mvc) I posed a while ago. It's the same technique the .NET MVC developers use for creating the form helpers (where they wrap the content body). – Joseph Woodward Apr 01 '15 at 07:44