我在使用MVC C#应用程序中的某些数据时遇到了一个小问题。
在控制器中,我有以下内容来检索要在视图中使用的数据集。
public ActionResult Franchisee()
{
getNav();
var data = (
from f in DietCenterDB.Franchises
join fc in DietCenterDB.FranchiseContents on f.ID equals fc.FranchiseId
into ffc
from subffc in ffc.DefaultIfEmpty()
select new {
State = f.State,
City = f.City,
AccountCode = f.AccountCode,
CenterNumber = f.CenterNumber,
FranchiseContentId = (subffc == null ? 0 : subffc.FranchiseContentId) }
).ToList();
return View(data);
}
视图包含以下代码
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Content.master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<dynamic>>" %>
<asp:Content ID="Head" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<h1>Franchisee Administration - <%: Html.ActionLink("Add New", "FranchiseeEdit", new { id = 0 }) %></h1>
» <%: Html.ActionLink("Content Management Home", "Index") %>
<p></p>
<table cellpadding="0" cellspacing="0" width="600px">
<%
int counter = 0;
string rowClass;
foreach (var item in Model) {
if ((counter % 2) == 0)
{
rowClass = "r1";
}
else
{
rowClass = "r2";
}
string dataString = item.State + " " + item.City + " " + item.AccountCode + " " + item.CenterNumber;
%>
<tr class="row <%: rowClass %>">
<td>
<%: Html.ActionLink(dataString, "FranchiseeEdit", new { id = item.ID, City = item.City, State = item.State, Zip = item.Zip })%>
</td>
<td align="right">
<%: Html.ActionLink("Edit Microsite Content", "MicrositeContentEdit", new { id = item.ID, City = item.City, State = item.State, Zip = item.Zip })%>
</td>
</tr>
<% counter++; %>
<% } %>
</table>
</asp:Content>
当我运行应用程序时,我收到以下错误
'object'不包含'State'的定义
调试时,调试器显示数据实际上在内存中。
非常感谢任何提示或线索!!!
答案 0 :(得分:1)
我会说这是因为你有一个动态的ViewPage,而不是强类型的:...
Inherits="System.Web.Mvc.ViewPage<IEnumerable<dynamic>>"
不是说它的问题,但会使事情变得棘手。
为什么不将查询投影到ViewModel中,并绑定到:
var data = (
from f in DietCenterDB.Franchises
join fc in DietCenterDB.FranchiseContents on f.ID equals fc.FranchiseId
into ffc
from subffc in ffc.DefaultIfEmpty()
select new MyViewModel {
State = f.State,
City = f.City,
AccountCode = f.AccountCode,
CenterNumber = f.CenterNumber,
FranchiseContentId = (subffc == null ? 0 : subffc.FranchiseContentId) }
).ToList();
然后在你的视图中:
Inherits="System.Web.Mvc.ViewPage<IEnumerable<MyViewModel>>"
修改强>
MyViewModel
是一个您需要创建的简单类,它允许为您的模型提供轻量级存储:
public class MyViewModel
{
public int State {get;set;}
public int City {get;set;}
public int AccountCode {get;set;}
public int CenterNumber {get;set;}
public int FranchiseContentId {get;set;}
}