garrigueta
garrigueta

Reputation: 7

concat string var in razor var name

I can't find anything to solve my problem in search, and here is my problem:

I'm using ASP.NET MVC 4 and EF 5, I'm trying to get a value from my db, but this db field depends on other var.

In Controller:

public ActionResult Products()
    {
        ViewBag.lang = "ENG";

        DataEntities db = new DataEntities();

        ViewBag.Categories = db.Categories;

        return View();
    }

In Template View:

<ul>
@{
    if (ViewBag.Categories != null)
    {
        foreach (var cat in ViewBag.Categories ) 
        {
            <!-- we need in this case "Name_ENG" -->
            var title = "Name_" + @ViewBag.lang;

            <li>@cat.(title)</li>
            <!-- out: cat.ToString() + "(title)" -->

            <li>@cat.(@title)</li>
            <!-- out: cat.ToString() + "(" + title.ToString() + ")" -->

            <li>@cat.@title</li>
            <!-- out: cat.ToString() +  title.ToString()  -->
        }
    }
}
</ul>

is there a way to get property "Name_ENG" from cat object like @cat.Name_ENG using a string ?

"In this case I'm trying to list al Categories in Products page."

Thanks a lot

Upvotes: 0

Views: 1588

Answers (3)

Krzysztof Kalinowski
Krzysztof Kalinowski

Reputation: 1461

Try this

<ul>
@{
    if (ViewBag.Categories != null)
    {
        foreach (var cat in ViewBag.Categories ) 
        {            
            // here you can do something on cat
            <text>
            <li>@(cat.title)</li>
            </text>
        }
    }
}
</ul>

I personally suggest you to pass the data to the view by parameter. And use @model in the view (strong type view).

Upvotes: 0

aleha_84
aleha_84

Reputation: 8539

here is an article from msdn. You can access EF entries properties by name. But at first you need dbContext and second it is wrong to access dbContext from view.

example:

object currentName2 = context.Entry(blog).Property("Name").CurrentValue;

Also, as mentioned in another answer, reflection:

object value = typeof(YourType).GetProperty("PropertyName").GetValue(yourInstance, null);

Upvotes: 0

walther
walther

Reputation: 13600

No, definitely not in c#. You'd have to use reflection for this to work (and the syntax would be different of course as well).

I think a better option would be to create a method that would retrieve the value based on a string input, like

public T GetValue<T>(string propertyName)

and call that from your view when needed

Upvotes: 1

Related Questions