如何在_Layout.cshtml中进行数据绑定

问题描述:

在ASP.NET WebForms中,我可以使用母版页的CodeBehind来获取用于绑定导航的数据.

In ASP.NET WebForms, I can use the CodeBehind of a master page to fetch data to use to bind up my navigation.

如何在ASP.NET MVC 3中实现相同的目标?

理想情况下,主导航将位于 _Layout.cshtml 中,但是此文件没有其自己的模型.即,它只能使用控制器操作提供的模型(假设 _Layout.cshtml 中的基类和 @model 指令.

Ideally the main navigation would be in the _Layout.cshtml but this file doesn't have it's own model. i.e. It can only use the model supplied by the controller action (assuming a base class and @model directive in the _Layout.cshtml.

修改
虽然我意识到MVC没有DataBinding的概念,但我在此处包括了它,以帮助描述我正在寻找的功能.

Edit
While I realise MVC does not have the notion of DataBinding, I included it here to help describe the functionality I'm looking for.

如何在ASP.NET MVC 3中实现相同的目标?

How can I achieve the same in ASP.NET MVC 3?

数据绑定的概念在MVC模式中并不常见.要实现导航,您可以使用 Html.Action和Html.RenderAction .

The notion of databinding is not common for the MVC pattern. To implement the navigation you could use Html.Action and Html.RenderAction.

示例:

public class NavigationController : Controller
{
    public ActionResult Index()
    {
        NavigationViewModel model = ...
        return View(model);
    }
}

,然后在布局内:

@Html.Action("Index", "Navigation")

index.cshtml可能是实现导航的部分.

The index.cshtml could be a partial which implements the navigation.