如何使用 viewbag 将一列数据作为列表传递到强类型视图

发布于 2024-11-05 11:32:02 字数 1013 浏览 1 评论 0原文

任何人都可以为我指明如何使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

渔村楼浪 2024-11-12 11:32:02

我鼓励您将根据 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?

清风夜微凉 2024-11-12 11:32:02

在我看来,ViewBag.customer 保存了Customers 的集合,而不是单个Customer 对象。在您的查询中,您应该有一个 where 部分。

It seems to me that ViewBag.customer holds a collection of Customers not a single Customer object. In your Query you should have a where part.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文