Aravin Aravin - 3 months ago 50
ASP.NET (C#) Question

Unable to display LINQ query output values from controller to view


public ActionResult Track(string awb)
ViewBag.Title = "Track Your Shipment";
ViewBag.ErrorMessage = string.Empty;
ViewBag.ShipmentNo = awb;
FLCourierDetail trackOutput = new FLCourierDetail();

if (awb != null)
trackOutput = db.FL_CourierDetail.SingleOrDefault(fLCourierDetail => fLCourierDetail.AWBNumber == awb);
if (trackOutput != null)
var courierId = db.FL_CourierDetail.Where(s => s.AWBNumber == awb).Select(s => s.Courier);
var currentStatus = (from c in db.FL_CourierDetail
join s in db.FL_CourierStatus
on c.Courier equals s.CourierId
where c.AWBNumber == awb
select new { awb = c.AWBNumber, staus = s.StatusId, updated = s.StatusId, remark = s.Remark }).ToList();
ViewBag.CurrentStatus = currentStatus;
ViewBag.ErrorMessage = "Shipment number not found.";
ViewBag.ErrorMessage = "Please provide valid Shipment number.";

return View(trackOutput);


<div class="col-md-6">
var status = ViewBag.CurrentStatus;

foreach (var item in status)

If I iterate using foreach or if loop I am able to see the data in debug, but I am not able to write in html.


enter image description here

Web Page

enter image description here


I am not able to read each value like awb, status, date etc.

enter image description here

Did I miss anything here?

Answer Source

The query result is an anonymous class, within the loop, each item is an object and thus the exception, object has now awb property.

One way to solve this is by defining a class:

public class Status {
    public string awb { get; set; }
    public int staus { get; set; }
    public int updated { get; set; }
    public string remark { get; set; }

Then your select would look like:

... select new Status { awb = c.AWBNumber, staus = s.StatusId, updated = s.StatusId, remark = s.Remark }).ToList();

Then, within the View:

var status = (List<Status>) ViewBag.CurrentStatus;

Another possible solution is to use strongly typed view model

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download