0

How do you access a strongly bound complex type in a webGrid within MVC 3. Example, I have an object called Project that has another object as a property called Employee. The two objects relate to each other on a primary key EmployeeId. If the project is the strongly bound object, how does one access any properties that belong to the employee class that is a property on the Project class?

I have searched around and have found the answer of using dot notation. (Employee.EmployeeId) but that does not work

is there a specific way to do this when binding the columns?

Thanks.

TampaRich
  • 793
  • 2
  • 9
  • 22

1 Answers1

1

The dot notation should work.

Model:

public class Project
{
    public string Name { get; set; }
    public Employee Employee { get; set; }
}

public class Employee
{
    public int EmployeeId { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = Enumerable.Range(1, 5).Select(x => new Project
        {
            Name = "project " + x,
            Employee = new Employee
            {
                EmployeeId = x
            }
        });
        return View(model);
    }
}

View:

@model IEnumerable<Project>

@{
    var grid = new WebGrid(Model);
}

@grid.GetHtml(
    columns: grid.Columns(
        grid.Column("Name"),
        grid.Column("Employee.EmployeeId")
    )
)

Result:

enter image description here

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928