0

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>
}
teo van kot
  • 12,350
  • 10
  • 38
  • 70
nam
  • 21,967
  • 37
  • 158
  • 332
  • 6
    you should'nt do that, use viewmodel, why you don't want to use it? – Ehsan Sajjad Aug 29 '16 at 20:13
  • 4
    Your linq expression returns a collection of anonymous objects. You cannot bind your view to that. You should create and use a view model/DTO – Shyju Aug 29 '16 at 20:15
  • Hardcoded viewmodels always good way to implement a view, if you do not have an exact irregular situation. – Cihan Uygun Aug 29 '16 at 20:20
  • 1. http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp-net-mvc-3-applications/ 2. just remove the entire line – JamieD77 Aug 29 '16 at 20:24

1 Answers1

0

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.

teo van kot
  • 12,350
  • 10
  • 38
  • 70
  • You also seem to be using ViewModel shown in you Index() method above. Did you mean vm not as a YmVievModel() class instance variable - instead just a variable for the LINQ Query? – nam Aug 29 '16 at 21:00
  • @nam that's not ViewModel actually. It's `Tuple` – teo van kot Aug 29 '16 at 21:02
  • I see - thanks. `MyViewModel vm= new MyViewModel(); ` line is not used. – nam Aug 29 '16 at 21:09
  • Now Tuple is the view model. What's in a name? – Gert Arnold Aug 29 '16 at 21:23
  • 1
    Are you sure about "You always can use Tuple". EF requires parameterless constructors and property setters, hence does not support projecting to `Tuple`s. See for instance [Create a Tuple in a Linq Select](http://stackoverflow.com/questions/33545249/create-a-tuple-in-a-linq-select/33545601#33545601). – Ivan Stoev Aug 29 '16 at 21:39