Click here to Skip to main content
15,894,017 members
Articles / Programming Languages / C#

Getting Information into the Layout Without Using ViewBag

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
12 Sep 2011LGPL3 16.3K  
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 allows you to do the following:

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

And in your _Layout.cshtml:

XML
<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:

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

Then add the following to your BaseController:

C#
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.

C#
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:

XML
<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)


Written By
Founder 1TCompany AB
Sweden Sweden

Comments and Discussions

 
-- There are no messages in this forum --