Foreign Key relationships in ASP.NET MVC
I have a parent table and a child table.
Parent Table: int AID, nvarchar parentname, nvarchar description
Child Table: int CID, int AID, nvarchar childname, nvarchar address
Child table has got a foreign key(AID) from parent table. I need to display the list of Child table in view page. I'm new to asp.net mvc and the problem is, I'm not able to get the parentname to be displayed along with the childtable.
As we have foreign key, it should be possible to get the parentname using AID. Can anybody sort开发者_如何学编程 it out using some simple example. I'm struggling with this for the last 7hours.
Consider the Parent table to be an account and child to be a list of contacts associated with the account.
Parent Table => PID,PName, PAddress
Child Table => CID,PID,CName,CAddressOutput Table => PName,CName,CAddress
Controller:
public ActionResult list()
{
var listing = db.child.FindContact().ToList();
return view(listing);
}
View snippet(.aspx):
<%: foreach(var a in Model) %>
{
<%: a.PName %>
<%: a.CName %>
<%: a.CAddress %>
}
Thanks.
First you need to create an object(ViewModel) that has all the properties from parent and a collection of children.
This is exactly how you need to do it..
http://stephenwalther.com/blog/archive/2009/04/13/asp.net-mvc-tip-50-ndash-create-view-models.aspx
精彩评论