Problem in ViewBag foreach in ASP.NET MVC view RRS feed

  • Question

  • User313375813 posted

    I have Three tables ( Participants, Activities, and enrolments) and the table Enrolments joint with both Participants and Activities using Lamda . I have writtern a Lamda query to join these tables to understant the number of activities each participant participated in. my query result is OK but the problem is while I want to foreach the result of View Bag to a table it gives me the list of returned value passed by view bag as below: My question is how to foreach the result of my query into table using ViewBag

    My Controller

    public ActionResult pReport(int? id)
                var nactivities = db.Activities
                           ac => ac.ActivityId,
                           en => en.ActivityId,
                           (enr, act) => new { en = enr, ac = act })
                           db.Participants.Where(pr => pr.ParticipantId == id),
                           en => en.ac.ParticipantId,
                           prt => prt.ParticipantId,
                           (enr, prt) => new { enr.ac.PostTestScore1, enr.ac.PostTestScore2, enr.ac.ActivityId, enr.ac.AttendFirstday, enr.ac.AttendSecondDay })
                       .Select(c => new
                ViewBag.data = nactivities;
                return View();

    <div class="portlet box green-jungle">
        <div class="portlet-title">
            <div class="caption">
                <span>TDR Participant Details/Reports (@ViewBag.name)</span>
        <div class="portlet-body">
            <table class="table">
                    @foreach (var item in ViewBag.data)


    Monday, September 24, 2018 8:45 AM

All replies

  • User-271186128 posted

    Hi zaker,

    Please refer to the following code to display the result:

    Code in view:

    <table class="table">
            @foreach (var item in ViewBag.data)

    Code in controller:

                List<Enrolments> itemlist = new List<Enrolments>()
                    new Enrolments(){ ActivityId=1001, PostTestScore1="A1" , PostTestScore2="B1", AttendFirstday="C1", AttendSecondDay = "D1" },
                    new Enrolments(){ ActivityId=1002, PostTestScore1="A2" , PostTestScore2="B2", AttendFirstday="C2", AttendSecondDay = "D2" },
                    new Enrolments(){ ActivityId=1003, PostTestScore1="A3" , PostTestScore2="B3", AttendFirstday="C3", AttendSecondDay = "D3" },
                    new Enrolments(){ ActivityId=1004, PostTestScore1="A4" , PostTestScore2="B4", AttendFirstday="C4", AttendSecondDay = "D4" },
                    new Enrolments(){ ActivityId=1005, PostTestScore1="A5" , PostTestScore2="B5", AttendFirstday="C5", AttendSecondDay = "D5" },
                ViewBag.data = itemlist;

    the output as below:

    Best regards,

    Tuesday, September 25, 2018 3:27 AM