i have an action named PackageIndex
in which i am creating a list type view of package class ..in this view i use layout in which i have to to display notification on navbar ...for that purpose i have to pass notification list to layout to display notification..my code is given below...
public ActionResult PackageIndex()
{
//feedback counter
int count = feedbackCounter();
ViewData["FeedbackCount"] = count;
int notificationcount = notificationCounter();
ViewData["notificationcount"] = notificationcount;
return View(db.packages.ToList());
}
in this action i also have to passs ( db.notification.ToList()
)...to provide data to layout ..i can't understand how to solve this...
You can create a model for this view, for example:
public class PackageIndexModel()
{
public List<Package> Packages { get; set; }
public int NotificationCount { get; set; }
public int FeedbackCount { get; set; }
}
and you can return this
var obj = new PackageIndexModel() { Packages = db.packages.ToList(), NotificationCount = notificationCounter(), FeedbackCount = feedbackCounter() };
return View(obj);
Or you could just set that object on a TempData:
TempData["Notifications"] = obj;
And in your _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;
}
}
EDIT: I think the second example is cleaner, because on don't have to receive your notifications on every view you create.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.