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
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
).