ASP.NET MVC 3 _Layout.cshtml Controller
Can anyone help me 开发者_如何学Gowith the subject? I'm using Razor view engine and I need to pass some data to _Layout. How can I do it?
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")
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.
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...
精彩评论