0

If I have a strongly typed view e.g. Inherits="System.Web.Mvc.ViewPage>" %> And i want to output the list of items in the model, when I use "Add view" within visual studio i get the following html code generated below. Is there anyway to eliminate the Magic string "Version" when outputting the table column headers?

<table>
    <tr>
        <th>
            Version
        </th>
     </tr>
    <% foreach (var item in Model) { %>
    <tr>
       <td>
          <%= Html.Encode(item.Version) %>
       </td>
    <tr/>
   <% } %>
</table>
LukeH
  • 263,068
  • 57
  • 365
  • 409
Noel
  • 3
  • 1

3 Answers3

1

What would you like to have instead?

You could use resource files so they are translated or something.. Or if it has to be the name of the item.Version variable you can probably look into some reflection.

Boris Callens
  • 90,659
  • 85
  • 207
  • 305
  • I was hoping you could use some strongly typed html helper to prevent the magic strings issues e.g for a single item in the list <%= Html.TextBoxFor(model => model.Version)%> – Noel Jan 18 '10 at 13:54
0

I think you'll have to use reflection. This question looks like it will help you:

How do you get a C# property name as a string with reflection?

Community
  • 1
  • 1
Nick
  • 5,616
  • 10
  • 52
  • 72
0

If you have your controllers and views in the web project, just add Resource Files (.resx) to App_GlobalResources (or App_LocalResources relative to the view, though I'm not a fan of that) and then reference the resources from yoru views.

I personally create a "Resources" project that contains a bunch of Resource Files (.resx). Each resx is set to public (dropdown at the top of the designer). This way they can be accessed from Views in the web project or controllers/application services in my other projects.

Having said that, unless sharing copy or translation is a major concern to you, it's ok to leave the copy in the views as a "magic string".

Richard Szalay
  • 83,269
  • 19
  • 178
  • 237