2

I have three objects:

public class Part
{
    [Key]
    public int ID { get; set; }
    public string Number { get; set; }
    public string Name { get; set; }
    public int descID { get; set; }    
}

public class Description
{
    [Key]
    public int descID { get; set; }
    public string descName { get; set; }
    public string description { get; set; }
}

public class GridPart
{
    public string name{ get; set; }
    public string number { get; set; }
    public string description { get; set; }            
}

I'm using LINQ to join Part and Description on the descID column:

public ActionResult Index()
{    
    var myParts = from p in db.Parts
                  join d in db.Description on p.descID equals d.DescriptorID
                  select new { Description = d.description, Name = p.name};
    List<GridPart> partsList = new List<GridPart>();

    foreach (var m in myParts)
    {
        GridPart gp = new GridPart();
        gp.Name = m.name;
        gp.description = m.description;                    
        partsList.Add(gp);
    }
    return View(partsList);
}

If I was just using the Parts table, in the view I would do:

@model IEnumerable<MyApp.Models.Part>

What do I do if I'm using the joined table? This uses both Parts and Description, not to mention my List of GridParts, how do I pass this through to display all of the data I need?

Any advice is greatly appreciated.

Darren
  • 1,352
  • 5
  • 19
  • 49
DavidB
  • 191
  • 1
  • 4
  • 14

1 Answers1

2

If you pass an anonymous type to your view it won't be strongly typed. You can refer to your model like this instead

@Html.TextBox("Name")

or

@Html.Display("Name")

Although this will work I would advice against it - The better solution would be to go with a Viewmodel instead. This will make your view strongly typed.

Edit: Looking on this again I see that your actually not parsing the anonymous type to your view. Your parsing a list of GridParts.

You should be able to strongly type your view like your tried - just refer to GridParts instead of parts.

@model IEnumerable<MyApp.Models.GridPart>
Community
  • 1
  • 1
Morten Anderson
  • 2,301
  • 15
  • 20