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>
}
4
  • 6
    you should'nt do that, use viewmodel, why you don't want to use it? Commented Aug 29, 2016 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 Commented Aug 29, 2016 at 20:15
  • Hardcoded viewmodels always good way to implement a view, if you do not have an exact irregular situation. Commented Aug 29, 2016 at 20:20
  • 1. rachelappel.com/… 2. just remove the entire line Commented Aug 29, 2016 at 20:24

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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 that's not ViewModel actually. It's Tuple
I see - thanks. MyViewModel vm= new MyViewModel(); line is not used.
Now Tuple is the view model. What's in a name?
Are you sure about "You always can use Tuple". EF requires parameterless constructors and property setters, hence does not support projecting to Tuples. See for instance Create a Tuple in a Linq Select.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.