Search code examples
c#asp.net-mvcentity-frameworkwebgrid

How to display navigation properties in a MVC/EF WebGrid


Lets say, I have the following model

public class MyObject {
    public String id { get; set; }
    public virtual Organisation organisation { get; set; }
    public int organisationId { get; set; }
}

public class Organisation {
    public int id { get; set; }
    public String name { get; set; }
}

I created a controller with a DbContext (ServiceContext) having a DbSet myObjects

public ActionResult Index() {
    ServiceContext context = new ServiceContext();
    context.myObjects.Include(o => o.organisation).ToList();
    return View(myObjects);
}

And a view

@model Enumerable<MyObject>
@{
    WebGrid grid = new WebGrid(Model);
}
<div>
    @grid.GetHtml()
</div>

The corresponding WebGrid is displayed but I dont know how to display the Organization name property as a grid column. By default only the organizationId field is displayed.

Any ideas? thank you.


Solution

  • This is working with the following code in the view (so simple ...)

    @grid.GetHtml(
        columns: grid.Columns(
            grid.Column(columnName:"organisation.name"),
        )
    )