1

In a View auto generated, I could see a couple of lines like:

<table>
<tr>
    <th>
        @Html.DisplayNameFor(model => model.RestarauntName)
    </th>
</tr>

I thought of writing something like this:

<table>
@{
            <th>
                 @typeof(Tutorial.Models.RestarauntReview).GetProperty("RestarauntName").Name
             </th>
        }

and it worked too!

So my guess is that the DisplayNameFor() method uses reflection to find the name of the corresponding property.

Here's something I break my head off.

  1. What is the cost of using reflection ?

  2. For smaller views that we want to be rendered quicky can we just type the name of the property ? (hardcoding ?)

1 Answer 1

2

So my guess is that the DisplayNameFor() method uses reflection

Not directly, I suspect. It's more likely that is uses ModelMetaData (which no doubt uses reflection eventually if you follow the trail).

For smaller views that we want to be rendered quicky can we just type the name of the property ?

You can. It might be ok for a fairly small and unchanging project but I wouldn't necessarily recommend it.

What is the cost of using reflection ?

I think you'll find it to be insignificant for most purposes. It's one of those cases in which it's not a concern unless it becomes a concern (duck, recursion!).

The greater concern is: Is reflection the best way to achieve my goal? I think that's the question you should be asking. Reflection is great fun (I know) but it's also a bit hard to read and can be hard to debug. That's why it's probably best to avoid it if there is an alternative. In this case there is: ModelMetaData.

What I mean by that is: do try to use HTML Helpers, and if they don't quite do what you want then try to extend them and create your own. Try to fall in love with Display Templates and Editor Templates and use them in conjunction with ModelMetaData.

The problem with using reflection in the Razor View is that you're putting the wrong things in the view. Views should be stupid - meaning they shouldn't have any logic in them or really be 'doing much' of anything. You just pass the views data and they'll display it for you.

I asked the (slightly related) question Are HTML helpers worth using with complex markup? which you might find interesting.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.