How can I databind in the _Layout.cshtml

2019-04-02 01:36发布

问题:

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

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

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.

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.

回答1:

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

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

Example:

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

and then inside the layout:

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

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