Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Getting information into the Layout without using ViewBag

, 12 Sep 2011 LGPL3
Rate this:
Please Sign up or sign in to vote.
How to get information into the Layout without using ViewBag.

You should avoid using the ViewBag as much as possible since you get runtime errors instead of compile time errors if something fails. The problem is that it can be hard to avoid it if you are using information in your layout.

The solution that I’m using lets you do the following:

public class YourController : BaseController
{
    public ActionResult YourAction()
    {
        LayoutModel.MetaDescription = "Does something in the application";
        return View();
    }
}

And in your _Layout.cshtml:

<meta name="description" value="@LayoutModel.MetaDescription" />

See? Everything is typed.

The approach I’m using is to create a base class for views and inherit WebViewPage in it. First things first, add a model for your layout:

public class LayoutViewModel
{
    public string MetaKeywords { get; set; }
}

Then add the following to your BaseController:

public class BaseController : Controller
{
    private LayoutViewModel _layoutModel = new LayoutViewModel();

    public LayoutViewModel LayoutModel { get { return _layoutModel; } }

    protected override void OnResultExecuting(ResultExecutingContext ctx)
    {
        var viewResult = ctx.Result as ViewResult;
        if (viewResult != null)
            viewResult.ViewBag.LayoutModel = LayoutModel;

        base.OnResultExecuting(ctx);
    }
}

OK, I know. I’m cheating and using the ViewBag. But since it’s only in one place, it’s less error prone than using the ViewBag everywhere.

Now create the view base class. You need to create two versions to have support for typed views.

public class ViewBaseWithLayoutModel : WebViewPage
{
    public LayoutViewModel LayoutModel { get { return (LayoutViewModel)ViewBag.LayoutModel; } }
}

public class ViewBaseWithLayoutModel<T> : WebViewPage<T>
{
    public LayoutViewModel LayoutModel { get { return (LayoutViewModel)ViewBag.LayoutModel; } }
}

The last thing is to specify your new base view class in your Views\Web.config:

<system.web.webPages.razor>
<pages pageBaseType="Namespace.To.ViewBaseWithLayoutModel">

That’s it.

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)

Share

About the Author

jgauffin
Founder Gauffin Interactive AB
Sweden Sweden
Founder of OneTrueError, a .NET service which captures, analyzes and provide possible solutions for exceptions.
 
blog | twitter
Follow on   Twitter   LinkedIn

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.1411028.1 | Last Updated 12 Sep 2011
Article Copyright 2011 by jgauffin
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid