简体   繁体   中英

How to display Linq to Entity query result in ASP.NET MVC view

I have a Link 2 Entity query expression in my ASP.NET MVC app:

Dim var = From c In context.Evaluation_Template _
          From ae In context.Assigned_Evaluation _
          Join ua In context.User_Assignment On ae.Assignment_ID Equals ua.Assignment_ID _
          Select c.Evaluation_Name, ae.Due_Date, ua.Is_Started, ua.Is_Completed, ua.Is_Approved

I want to pass this to the view and display the results.

I have tried

Return View(var)

But I'm not sure how to iterate through the results.

I'm new to .NET in general so any help would be greatly appreciated.

If you want strongly-typed objects to use in your view you would need to go into your view and change the top from...\\

<%@ Page Language="VB" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

to

<%@ Page Language="VB" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage(Of IEnumerable(Of String))" %>

Of course replacing Of String with your model type you want to pass in. To pass in your collection you would use...

Return View(query.ToList())

... assuming query was some sort of IQueryable query from ADO.NET EF.

Then in your view you could iterate through the results passed in.

    <%  For Each s As String In Model
        %><%=s%><%
    Next%>

That would output each string in the collection passed into the view's data model.

Though I do recommend for best practices to create a type specifically for passing into your views, aka ViewData.

First it looks like your query is messed up a tiny bit. I am unsure about VB.NET but you would in this case need a separate class because you are selecting something that is not your Entity Framework model.

Dim var = From c In context.Evaluation_Template
          .Include("Assigned_Evaluation")
          .Include("User_Assignment")
          Select c

This is the third eidt, I keep posting it :) What your view page then needs to take is:

IEnumerable<Evaluation_Template>

You do this either by generating a strongly typed view or setting it in the page directive of the view page. You could also do what you are trying for (less overhead) but then you would need a separate class to send to the view page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM