如何使用 viewbag 将一列数据作为列表传递到强类型视图
任何人都可以为我指明如何使用 viewbag 将列表中的一列数据传递到强类型视图的正确方向。我正在使用强类型视图传递 CustomerSites 列表。我还想在列表中每个 CustomerSite 旁边显示 CustomerName。
我已尝试以下方法,但由于控制器返回客户列表,因此它不允许我从视图访问 CustomerName 属性,是否可以从视图访问此属性?
public ViewResult Index()
{
var q = from a in db.Customers.ToList()
select a;
ViewBag.customer = q;
return View(db.CustomerSites.ToList());
}
@model IEnumerable<trsDatabase.Models.CustomerSite>
@foreach (var customer in Model)
{
<tr>
<td>
@ViewBag.customer.CustomerName
</td>
<td>
@customer.UnitNo
</td>
<td>
@Truncate(customer.StreetName, 25)
</td>
<td>
@customer.Town
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=customer.Id }) |
@Html.ActionLink("Details", "Details", new { id=customer.Id }) |
@Html.ActionLink("Delete", "Delete", new { id=customer.Id })
</td>
</tr>
}
Can anyone point me in the right direction as to how to pass one column of data in a list using viewbag to a strongly typed view. I am passing a list of CustomerSites using a strongly typed view. I would also like to display a CustomerName next to each CustomerSite in the list.
I have tried the following approach, but as the controller is returning a list of customers it wont let me access the CustomerName property from the view, is it possible to access this property from the view?
public ViewResult Index()
{
var q = from a in db.Customers.ToList()
select a;
ViewBag.customer = q;
return View(db.CustomerSites.ToList());
}
@model IEnumerable<trsDatabase.Models.CustomerSite>
@foreach (var customer in Model)
{
<tr>
<td>
@ViewBag.customer.CustomerName
</td>
<td>
@customer.UnitNo
</td>
<td>
@Truncate(customer.StreetName, 25)
</td>
<td>
@customer.Town
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=customer.Id }) |
@Html.ActionLink("Details", "Details", new { id=customer.Id }) |
@Html.ActionLink("Delete", "Delete", new { id=customer.Id })
</td>
</tr>
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我鼓励您将根据 CustomerSites 和 CustomerNames 构建的 ViewModel 传递给 View。为什么不从由客户名称和站点组成的数据库对象中获取?
I would encourage you to pass to the View a ViewModel built out from CustomerSites and CustomerNames. Why don't you get from the DB object which consists from Customer name and site?
在我看来,
ViewBag.customer
保存了Customers
的集合,而不是单个Customer
对象。在您的查询中,您应该有一个where
部分。It seems to me that
ViewBag.customer
holds a collection ofCustomers
not a singleCustomer
object. In your Query you should have awhere
part.