Franziee
Franziee

Reputation: 649

MVC 4 How to display foreign key related data in view?

I have two classes generated from my database by EF 6:

class Person {
    public int PID { set; get; }
    public string Name { set; get; }
    public int CountryID { set; get; }

    public virtual ICollection<Country> Country { set; get;}
}

class Country {
    public int CID { set; get; }
    public string Name { set; get; }
}

I would like to show data in a table as follows:

Person Name ^v                 Countries ^v                 Operation
----------------------------- ----------------------------- ---------------
[___________________________] [________dropdown_________|v] [Edit] [Delete]
...
[___________________________] [________dropdown_________|v] [Edit] [Delete]
[Pager]

In my database CountryID is a foreign key to Country.CID. I would like to show data and allow to in line editing and/or deleting. The columns have to be disabled but in edit mode of course enabled instead.
I googled a lot and read stackoverflow too but didn't found a comprehensive help for this.

Does anybody has an example how to do this gridview?
Thanks a lot

Upvotes: 1

Views: 7116

Answers (2)

Nirav Parmar
Nirav Parmar

Reputation: 451

You can try this:

Controller

public ActionResult Index()
{
var persons = db.Person.Include(c => c.Country);
return View(persons.ToList());
}

View

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.PersonName)
    </td>       
    <td>
        @Html.DisplayFor(modelItem => item.Country.CountryName)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id=item.PersonID }) |            
        @Html.ActionLink("Delete", "Delete", new { id=item.PersonID })
    </td>
</tr>

Upvotes: 2

Ganesh Todkar
Ganesh Todkar

Reputation: 537

http://www.jtable.org/demo/PagingAndSorting

You can also find some good nuget packages for inline editing grid.

Upvotes: 0

Related Questions