【问题标题】:how can pass more than one query object to a view如何将多个查询对象传递给视图
【发布时间】:2016-06-28 19:44:16
【问题描述】:

我有一个名为PackageIndex 的操作,我在其中创建包类的列表类型视图。在这个视图中,我使用布局,我必须在导航栏上显示通知...为此我必须将通知列表传递给布局以显示通知..我的代码如下...

  public ActionResult PackageIndex()
        {
            //feedback counter
            int count = feedbackCounter();
            ViewData["FeedbackCount"] = count;
            int notificationcount = notificationCounter();
            ViewData["notificationcount"] = notificationcount;
            return View(db.packages.ToList());
        }

在此操作中,我还必须通过 (db.notification.ToList())...为布局提供数据..我不明白如何解决这个问题...

【问题讨论】:

标签: c# asp.net-mvc asp.net-mvc-3 asp.net-mvc-4


【解决方案1】:

您可以为此视图创建模型,例如:

public class PackageIndexModel()
{
    public List<Package> Packages { get; set; }
    public int NotificationCount { get; set; }
    public int FeedbackCount { get; set; }
}

你可以退货

var obj = new PackageIndexModel() { Packages = db.packages.ToList(), NotificationCount = notificationCounter(), FeedbackCount = feedbackCounter() };
return View(obj);

或者您可以只在 TempData 上设置该对象:

TempData["Notifications"] = obj;

在你的 _Layout.cshtml 中:

@{
    if (TempData["Notifications"] != null)
    {
        foreach (var notification in ((PackageIndexModel)TempData["Notification"]).Packages)
        {
            <script type="text/javascript">
                jQuery(document).ready(function () {
                    alert('@notification.Message');
                });
            </script>
        }

        TempData["Notifications"] = null;
    }
}

编辑: 我认为第二个示例更简洁,因为不必在您创建的每个视图上都收到通知。

【讨论】:

  • 如果我遵循第二种情况,那么我还必须制作 'packageIndexmodel' 或者这对于仅第一种情况是必不可少的。
  • 不,你没有。您可以将字符串列表传递给您的临时数据,您的 foreach 将是这样的: foreach (var notification in (List)TempData["Notification"])
  • @model IEnumerable&lt;WebApplication5.Models.Feedback&gt; &lt;table class="table"&gt; @foreach (var item in (List&lt;string&gt;)TempData["Notification"]){ &lt;tr&gt; &lt;td&gt; &lt;b class="label label-primary"&gt; @Html.DisplayFor(modelItem =&gt; item.email)&lt;/b&gt; &lt;p&gt;send feedback about&lt;/p&gt;&lt;b class="label label-primary"&gt;@Html.DisplayFor(modelItem =&gt; item.subject)&lt;/b&gt; &lt;hr /&gt; &lt;/td&gt; &lt;/tr&gt; } &lt;/table&gt; 项目不包含任何电子邮件获取错误...
  • 当然,您设置了一个字符串列表并尝试访问电子邮件属性。
  • 如果您在 tempdata 中使用 list os 字符串,它就是那个字符串。如果您在临时数据中设置包列表,则您拥有该对象的所有属性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-30
  • 1970-01-01
  • 1970-01-01
  • 2016-07-28
  • 1970-01-01
  • 1970-01-01
  • 2015-10-02
相关资源
最近更新 更多