ASP.NET MVC 3 _Layout.cshtml Controller

2019-01-27 17:23发布

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条回答
唯我独甜
2楼-- · 2019-01-27 17:58

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.

查看更多
\"骚年 ilove
3楼-- · 2019-01-27 18:02

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

查看更多
迷人小祖宗
4楼-- · 2019-01-27 18:03

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")
查看更多
登录 后发表回答