Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
560 views
in Technique[技术] by (71.8m points)

asp.net - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...