0

This is in my controller:

public ActionResult Index()
{
        var groupJoin = from d in db.tblParent1
                        join e in db.tblParent2 on d.parent1ID equals e.parent1ID
                        select new
                        {
                            parent1ID = d.parent1ID,
                            parent1Name = d.parent1Name,
                            parent2ID = e.parent2ID,
                            parent2Name = e.parent2Name,
                        };
        ViewBag.groupJoin = groupJoin.ToList();
        return View();
}

This is my view:

@foreach (var item in ViewBag.groupJoin)
{
    <tr>
         <td>
                @item.parent1Name
         </td>
         <td>
                @item.parent2Name
         </td>
   </tr>
}

I get this error :

object does not contain a definition for parent1Name

when replacing @item.parent1Name with @item. It displays the whole row like this in the web

{ parent1ID = 1, parent1Name = master , parent2ID = 2, parent2Name = child }

How can I specify a column?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 2
    You are not applying foreach on IQueryable, Its List. – habib Aug 04 '19 at 12:19
  • 3
    Maybe, because your result object is anonymous, the poroperties is not recognizable, try use a predifined type – Seyedraouf Modarresi Aug 04 '19 at 12:29
  • Possible duplicate of [Dynamic Anonymous type in Razor causes RuntimeBinderException](https://stackoverflow.com/questions/5120317/dynamic-anonymous-type-in-razor-causes-runtimebinderexception) – Eugene Podskal Aug 04 '19 at 12:38

1 Answers1

3

Define a class like this

public class Result
{
   public int parent1ID    { get; set; }
   public string parent1Name  { get; set; }
   public int parent2ID    { get; set; }
   public string parent2Name  { get; set; }
}

And do the following

var groupJoin = from d in db.tblParent1
                    join e in db.tblParent2 on d.parent1ID 
equals e.parent1ID
                    select new Result
                    {
                        parent1ID = d.parent1ID,
                        parent1Name = d.parent1Name,
                        parent2ID = e.parent2ID,
                        parent2Name = e.parent2Name,
                    };