-2

I want to write column name dynamically in a collection. My collection is in ViewBag and in ViewData.

I am trying

@{foreach (var item in ViewData["example"] as List<exampleList> )
                            {
                            <h1>@item["column" + column_id]</h1>

and item[ in above code gives error.

and also I have tried

@{foreach (var item in ViewBag.example )
                            {
                            <h1>@item.(column + column_id)</h1>

Also not working.

I just want to write the column name by myself in h1. I dont want intellisense choose for me. There are language suffixes at the end of everycolumn in my table.

such as name_fr, name_de, name_en

I just want to bring culture code there. For example: name + culture code.

If I type @item.name_fr It works. But I want to put there "fr" dynamically.

exampleList is just a class created by Ado.net entity data model. There is no problem with the class. It is a simple class. It doesn't have any data annotations.

The error is "Cannot apply indexing with [] to an expression of type"

What can be my mistake? What I am trying to get is possible or not?

oneNiceFriend
  • 6,691
  • 7
  • 29
  • 39
  • 1
    What do you mean _write column name_? What is your `exampleList` model and what are you trying to output? –  May 23 '16 at 10:22
  • 1
    What is `exampleList`? I suppose it is a class, can you post its definition? Can it handle indexing like `["column" + column_id]`? – Andrei May 23 '16 at 10:24
  • Yeah , thank you all. I have added your answers by editing my question. – oneNiceFriend May 23 '16 at 10:46

1 Answers1

1

You simply can't do that, if you really want to load some property of a object by using the property name as a string, you need to use reflection.

But I would suggest not to do it that way, using reflection to get property values in view thread might be a big performance hit.

A better way to do it would be using a Dictionary for this purpose. There you can store values using strings and get it.

Demo

Dictionary<string,object> d = new Dictionary<string,object>();
d.Add("name_fr",name_fr) ;
d.Add("name_de",name_de) ;
d.Add("name_en",name_en) ;

And in view:

<h1>@item.YourDictionaryProperty[column +"_"+ column_id]</h1>

Hope it makes sense.

SamGhatak
  • 1,487
  • 1
  • 16
  • 27
  • Thanks for your suggestion, but where to initialize that Dictionary? I tried to initialize in class' constructor, It doesnt work. I tried to initialize inside the dictionary property in class, It gives error: a field initializer cannot reference the non-static fiedl method or property.... – oneNiceFriend May 23 '16 at 12:08
  • Dictionary can be instantiated inside the constructor and values can be added runtime. – SamGhatak May 23 '16 at 12:13