Reputation: 1250
In the HomeController.cs I have the following snippet
public ActionResult Index()
{
var context = new DataClassesContext();
var regionBoudaries = from boundaryDetails in context.RegionBoundaries
join boundaryID in context.Region_Boundaries on boundaryDetails.RegionBoundaryID equals boundaryID.BoundaryID
select new { boundaryDetails.lat, boundaryDetails.@long, boundaryID.RegionID };
ViewData["RegionBoudaries"] = regionBoudaries;
return View();
}
In the View file I wrote
<%= ViewData["RegionBoudaries"] %>
Rather than the result of the query, I've got the whole LINQ query translated into SQL language. Can you help me get the result of the query? Thank you
Upvotes: 0
Views: 140
Reputation: 1039060
Sure you need to execute the query:
ViewData["RegionBoudaries"] = regionBoudaries.ToList();
But from what I can see you are using an anonymous object which would make it hard to access in view. So I would recommend you defining a model:
public class RegionViewModel
{
public double Latitude { get; set; }
public double Longitude { get; set; }
public int RegionID { get; set; }
}
and then adapt your query:
var context = new DataClassesContext();
var regionBoudaries =
from boundaryDetails in context.RegionBoundaries
join boundaryID in context.Region_Boundaries on boundaryDetails.RegionBoundaryID equals boundaryID.BoundaryID
select new RegionViewModel
{
Latitude = boundaryDetails.lat,
Longitude = boundaryDetails.@long,
RegionID = boundaryID.RegionID
};
The next step in improving your code is to of course get rid of this ViewData
crap and get full advantage of the view model you have defined and strong typing in your view:
public ActionResult Index()
{
using (var context = new DataClassesContext())
{
var regionBoudaries =
from boundaryDetails in context.RegionBoundaries
join boundaryID in context.Region_Boundaries on boundaryDetails.RegionBoundaryID equals boundaryID.BoundaryID
select new RegionViewModel
{
Latitude = boundaryDetails.lat,
Longitude = boundaryDetails.@long,
RegionID = boundaryID.RegionID
};
return View(regionBoudaries.ToList());
}
}
and now your view will become strongly typed to the view model:
<%@ Page
Language="C#"
Inherits="System.Web.Mvc.ViewPage<IEnumerable<RegionViewModel>>"
%>
and now you get strong typing and Intellisense:
<% foreach (var region in Model) { %>
<div>
Lat: <%: region.Latitude %>, Lon: <%: region.Longitude %>
</div>
<% } %>
Upvotes: 3