这是因为您已经选择Value
并且Value
没有Value
. 您应该更改控制器:
var yyy = (from a in Connection.Db.Authorities select a.Value);
到
var yyy = (from a in Connection.Db.Authorities select a);
或将视图更改为
@foreach(var item in ViewBag.data)
{
@item
}
////////////////////////////////////////编辑/ ///////////////////////////////////////
比你应该不使用匿名对象。你应该创建ViewModelClass
. 例如:
public class AuthoritiesViewModel
{
public string Value { get; set; }
public string TypeCode { get; set; }
public string Return { get; set; }
}
并更改您的控制器:
var yyy = (from a in Connection.Db.Authorities select new AuthoritiesViewModel{ Value = a.Value, TypeCode = a.TypeCode, Return = Calculate(a.Return)});
ViewBag.data = yyy;
在您看来,您将能够使用:
<table>
<tr>
<th>Value</th>
<th>TypeCode</th>
<th>Return</th>
</tr>
@foreach(AuthoritiesViewModel item in ViewBag.data)
{
<tr>
<td>@item.Value<td>
<td>@item.TypeCode<td>
<td>@item.Return<td>
</tr>
}
</table>
另外,我有一个问题要问你。为什么你使用ViewBag
从控制器传递数据到视图?您为什么不使用 Model 将这些数据传递给根据 MVC 模式查看?
//////////////////////////////////////// 更多编辑//////////////////////////////////////
发送多个查询结果您可以创建更复杂的模型。例如:
public class AuthoritiesViewModel
{
public string Value { get; set; }
public string TypeCode { get; set; }
public string Return { get; set; }
}
public class AnotherQueryViewModel
{
public string AnotherQueryValue { get; set; }
public string AnotherQueryTypeCode { get; set; }
public string AnotherQueryReturn { get; set; }
}
public class ModelClass
{
IEnumerable<AuthoritiesViewModel> Authorities { get; set; }
IEnumerable<AnotherQueryViewModel> AnotherQueryResults { get; set; }
}
并更改控制器:
var yyy = (from a in Connection.Db.Authorities select new AuthoritiesViewModel{ Value = a.Value, TypeCode = a.TypeCode, Return = Calculate(a.Return)});
// do your another select
var zzz = (from smthing select new AnotherQueryViewModel ...)
// create model instance
ModelClass model = new ModelClass()
{
Authorities = yyy.AsEnumerable(),
AnotherQueryResults = zzz..AsEnumerable()
}
// return view with model
return View("view", model);
并鉴于您可以使用:
@model ModelClass
@*display first query result*@
<table>
<tr>
<th>Value</th>
<th>TypeCode</th>
<th>Return</th>
</tr>
@foreach(AuthoritiesViewModel item in Model.Authorities)
{
<tr>
<td>@item.Value<td>
<td>@item.TypeCode<td>
<td>@item.Return<td>
</tr>
}
</table>
@*display second query result*@
<table>
<tr>
<th>Another Query Value</th>
<th>Another Query TypeCode</th>
<th>Another Query Return</th>
</tr>
@foreach(AnotherQueryViewModel item in Model.AnotherQueryResults)
{
<tr>
<td>@item.AnotherQueryValue<td>
<td>@item.AnotherQueryTypeCode<td>
<td>@item.AnotherQueryReturn<td>
</tr>
}
</table>