当然你需要执行查询:
ViewData["RegionBoudaries"] = regionBoudaries.ToList();
但据我所知,您正在使用一个匿名对象,这将使其难以在视图中访问。所以我建议你定义一个模型:
public class RegionViewModel
{
public double Latitude { get; set; }
public double Longitude { get; set; }
public int RegionID { get; set; }
}
然后调整您的查询:
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
};
改进代码的下一步当然是摆脱这种ViewData
废话并充分利用您定义的视图模型和视图中的强类型:
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());
}
}
现在您的视图将成为视图模型的强类型:
<%@ Page
Language="C#"
Inherits="System.Web.Mvc.ViewPage<IEnumerable<RegionViewModel>>"
%>
现在你得到了强类型和智能感知:
<% foreach (var region in Model) { %>
<div>
Lat: <%: region.Latitude %>, Lon: <%: region.Longitude %>
</div>
<% } %>