MVC 4母版页_Layout传递数据

ADC*_*ADC 0 c# asp.net-mvc razor asp.net-mvc-4

我有一个名为_Layout.cshtml并放置在文件夹中的母版页Views/Shared/_Layout.cshtml。我创建了一个控制器:SharedController.cs将数据传递给_Layout.cshtml 但不进入控制器。如何将数据传递到每个加载母版页_Layout.cshtml

这是控制器,例如:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace HAnnoZero.Controllers
{
    public class SharedController : Controller
    {
        public ActionResult _Layout()
        {
            ViewBag.help = "ciao";
            return View();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*att 5

首先,不要将其称为母版页。那是来自Web Forms。在MVC中,_Layout.cshtml是一种“布局”。这可能看起来像语义,但区分是很重要的,因为在 Web 窗体中,母版页本身就是一个真正的页面,背后有自己的代码。在 MVC 中,布局只是带有一些占位符的 HTML 模板。控制器,特别是被请求的控制器的动作,全权负责页面上下文。这也意味着您不能有一个_Layout向布局添加上下文的操作,因为该操作没有被调用,即使您这样做了(通过访问/Shared/_Layout浏览器中的 URL ,它会在_Layout.cshtml作为视图加载时失败,因为它需要一个肤浅的视图来填充对@RenderBody().

如果您想在布局中使用自己的上下文渲染某些内容,则必须使用子操作:

控制器

[ChildActionOnly]
public ActionResult Something()
{
    // retrieve a model, either by instantiating a class, querying a database, etc.
    return PartialView(model);
}
Run Code Online (Sandbox Code Playgroud)

东西.cshtml

@model Namespace.To.ModelClass

<!-- HTML that utilizes data from the model -->
Run Code Online (Sandbox Code Playgroud)

_Layout.cshtml

@Html.Action("Something", "ControllerSomethingActionIsIn")
Run Code Online (Sandbox Code Playgroud)