10

Can anyone help me with the subject? I'm using Razor view engine and I need to pass some data to _Layout. How can I do it?

3 Answers 3

10

As usual you start by creating a view model representing the data:

public class MyViewModel
{
    public string SomeData { get; set; }
}

then a controller which will fetch the data from somewhere:

public class MyDataController: Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            SomeData = "some data"
        };
        return PartialView(model);
    }
}

then a corresponding view (~/Views/MyData/Index.cshtml) to represent the data:

@{
    Layout = null;
}
<h2>@Model.SomeData</h2>

and finally inside your _Layout.cshtml include this data somewhere:

@Html.Action("index", "mydata")
Sign up to request clarification or add additional context in comments.

2 Comments

This would imply you have to add this manually to every view. Is there a way to pass data to the _layout.cshtml for every page?
@Anthony Gatlin, absolutely not. You could perfectly fine write @Html.Action("index", "mydata") in your _Layout => which would of course automatically add it to every page of your application that uses this layout.
1

You could use the ViewBag to pass data.

In your controller:

ViewBag.LayoutModel = myData;

Access in you layout:

@ViewBag.LayoutModel

It is a dynamic object, so you can use any property name you want.

Comments

1

The ViewBag method is the easiest. However if you need advanced and typed features, you can also try taking that part to a partial view (the part that'll render the dependent section) with a common controller (if the value can be calculated on it's own and doesn't need input from other controllers), and call RenderPartial on it from _Layout.
If you'd like I can give you some more info about it...

1 Comment

Yes, please, give us some more info about it :]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.