Vini
Vini

Reputation: 2134

Access properties in ViewModel in MVC

I have a viewmodel class with two properties (Both of them objects of other classes). I am able to access the variables from the parent class using

 @Model.Parent.ParentProperty1

But I am not able to access the variables in the child class with the statement

 @Model.Child.Property1

My ViewModel (Excerpt)

 public virtual Parent parent {get;set}
 public virtual IEnumerable<Child> Children {get;set;}

Child class has a reference to the parent class in its definition.

What i am trying to achieve

I want to access the parent property from the child class. Something like

 @Model.Child.ParentProperty1
        or
 @Model.Child.Property1

When i try to access the properties the intelisense suggests me functions that could be applied on IEnumerable.

Is there a way through which i can access the property values?

PS : I am trying to access the variable sin my View.

Upvotes: 1

Views: 1318

Answers (1)

Thijs
Thijs

Reputation: 3055

Well intellisense is correct. You're trying to an access IEnumerable. You can access specific elements from an IEnumerable using the ElementAt-function. Here is an example for the first element:

@Model.Children.ElementAt(0)

My guess is that you want to loop over your child-elements? You can do that by using a foreach:

@foreach(var child in Model.Children)
{
    var parent = child.Parent;
}

Upvotes: 1

Related Questions