如何将多个查询对象传递给视图

时间:2016-06-28 19:44:17

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

我有一个名为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())...来为布局提供数据..我无法理解如何解决这个问题......

1 个答案:

答案 0 :(得分:0)

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

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;
    }
}

编辑: 我认为第二个例子比较干净,因为不必在你创建的每个视图上收到通知。

相关问题