Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Data to a Layout Page

I have a layout page that has variables that need to be filled. Example:

@ModelType KarateAqua.schoolModel

<html>
    <body>

        @RenderBody()

        <div id="footer">
            <div class="content">
                <div class="bottom_logo">
                    <a href="/"><span class="inv">@Model.schoolName</span></a>
                </div>
            </div>
        </div>
    </body>
</html>

I don't want to populate this in every ActionResult. Is there a way to pass data to a layout page once and do it for all instances?

like image 999
Rupert Avatar asked May 11 '12 13:05

Rupert


2 Answers

OK since you want this to be set once you can make use of a partial view. However depending on your needs you will need to have several partial views (may be not ideal if sections are going to be scattered across the _layout page)

your partial view will look like

@model KarateAqua.schoolModel

<div class="bottom_logo">
<a href="/"><span class="inv">@Model.schoolName</span>
</div>

Controller

public class SchoolController : Controller
{
     public ActionResult Index()
     {
          //get schoolModel  
          return PartialView(schoolModel);
     }
}

in your _layout.cshtml place this line where you want to have the partial view to be inserted

@Html.Action("Index","School")
like image 172
Prashanth Thurairatnam Avatar answered Dec 06 '22 20:12

Prashanth Thurairatnam


Create an action filter and decorate your controller classes. Inside the action filter you have access to put values in the viewbag which are available to your layout.

This will run on each request and you will not have to set the values in each action. You can look for and ignore things like a child request and ajax requests which typically do not use the layout anyways and not set your viewbag values for those.

Below is a sample of an attribute i created to copy an object from the session and make it available to the layout via the ViewBag

public class CurrentUserAttribute : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        // Don't bother running this for child action or ajax requests
        if (!filterContext.IsChildAction && !filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
        {

            if (filterContext.HttpContext.Session != null)
            {
                var currentUser = filterContext.HttpContext.Session["CurrentUser"] as CurrentUser;
                if (currentUser != null)
                {
                    filterContext.Controller.ViewBag.CurrentUser = currentUser;
                }
            }
        }
    }


}
like image 38
JBeckton Avatar answered Dec 06 '22 19:12

JBeckton