Question

I have a view, and naturally, its own ViewModel:

@model TransportViewModel 

I'm using an EditorFor to show a property list of one of my ViewModel Objects:

@Html.EditorFor(model => model.Car.WheelPropertyList)

Inside my EditorFor I can easily show my properties:

@model WheelProperty
@Html.Label(Model.PropertyA)
@Html.Label(Model.PropertyB)

My question is: How can I access the "root" of my ViewModel from within the EditorFor? The code written above is accessing:

TransportViewModel.Car.WheelPropertyList.ElementAt(n).PropertyA TransportViewModel.Car.WheelPropertyList.ElementAt(n).PropertyB

This is understood. The question is, how can I access, for instance:

TransportViewModel.Train.ModelList.ElementAt(0).Name

From within my EditorFor?

I know it is possible to solve this issue using the ViewBag. However, I've always heard that if your ViewModel is perfect, you'll never need to use any ViewBag at all. Is this true or should I really use a ViewBag in this particular case?

Était-ce utile?

La solution

One way is to provide a reference to the root object in the child object:

public class TransportViewModel  
{
    public List<WheelProperty> WheelPropertyList {get;set;}
    ...
}

public class WheelProperty
{
    public TransportViewModel TransportView {get;set;}
    public string PropertyA {get;set;}
    public string PropertyB {get;set;}
    ...
}

Then your Editor can easily reference the properties of the root object.

Autres conseils

you can do like this to access the properties of Car:

foreach(var item in Model.Car.WheelPropertyList)
{
<span>@item.PropertyA</span>
<span>@item.PropertyB</span>
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top