How to access IQueryable in Razor?

Go To StackoverFlow.com

0

I’m building MVC3 “code first” application and to display data on my page I’m using the following:
Controller Code:

public ViewResult Index()
{
dynamic assignedT = from t in db.AssignedTasks

join a in db.Approvers on t.ApproverID equals a.ID
 join r in db.Requestors on t.RequestorID equals r.ID
 select new {Approver =a.FirstName + " " +a.LastName,
 Requestor=r.FirstName + " " + r.LastName,
 Title = t.Title,
 t.RequestedDate,
 t.CompletedDate, t.Description,
 Status =(int)t.InternalStatut
  };

 return View(assignedT);
    }

and on the page:

@{
   ViewBag.Title = "Index";
 }
<h2>Index</h2>
 <table>
  @foreach (var item in Model) {     
 <tr> 
   <td>@item.GetType().GetProperty("Title").GetValue(item, null)
   </td> 
   </tr> 
   } 
</table>

I know that using dynamic is not the best way. How to achieve same functionality using strongly-typed view? Thank you

2012-04-04 20:39
by Yuri


1

You can define the following class:

public class MyViewModel
{
    string Approver { get; set; }
    string Requestor { get; set; }
    string Title { get; set; }
    DateTime RequestedDate { get; set; }
    DateTime CompletedDate { get; set; }
    string Description { get; set; }
    int Status { get; set; }
}

If you then change select new in your Linq query to select new MyViewModel then you have a strongly typed viewmodel (and dynamic to var).

2012-04-04 20:43
by Wouter de Kort
i tryed to use List assignedT=... but getting cast exception. thank yo - Yuri 2012-04-04 21:16
Thank you @model System.Data.Entity.Infrastructure.DbQuery solved the problem!! - Yuri 2012-04-04 23:28
Ads