nam nam - 3 months ago 20
C# Question

How to send LINQ query to a View without using ViewModel

I can use a ViewModel and pass my LINQ Query through it to the View with @model directive as

@model IEnumerable<MyWebProject.ViewModels.MyViewModel>
. Question: But, 1. What if I don't want to use a View Model in the following example: 2. What would be my @model directive in that case?

ViewModel:

public class MyViewModel
{
public string CustomerName{ get; set; }
public int CustomerOrderNo{ get; set; }
}


Controller:

public ActionResult Index()
{
MyViewModel vm= new MyViewModel();
var vm = (from c in db.Customers
join o in db.Orders
select new { CustomerName = c.Name, CustomerOrderNo = o.OrderNo}).ToList();
return View(vm);
}


View:

@model IEnumerable<MyWebProject.ViewModels.MyViewModel>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.CustomerName)
</td>
<td>
@Html.DisplayFor(modelItem => item.CustomerOrderNo)
</td>
</tr>
}

Answer

You always can use Tuple. Like this:

public ActionResult Index()
{
    MyViewModel vm= new MyViewModel();
    var vm = (from c in db.Customers
             join o in db.Orders
             select new Tuple<string, int>(c.Name, o.OrderNo).ToList();
            return View(vm);
}

And on View:

@model IList<Tuple<string, int>>

You can access it like this:

@foreach (var item in Model)
{
    @Model.Item1
}

But DON'T DO IT, PLEASE.