你是如何做到这一点的? 此 View 是自动生成的。 例如,当我手动添加 View 时:其中包含 Index.cshtml 文件的联系人 View 。
我可以通过编写 Controller 联系人来修改此 View 。
public class ContactController : Controller
{
public ActionResult Index()
{
@ViewBag.Test = "this text will be used in my Contact View";
return View();
}
}
所以在我的联系人 View 中我可以这样做
<p> @Viewbag.Test </p>
然后会显示文本。 但是如何在我的共享 View 中为我的 _Layout.cshtml 文件实现这一点? 我通过添加 SharedController 进行了同样的尝试,但没有以这种方式工作
最佳答案
您不能为 _Layout.cshtml 设置 Controller 。该文件用于任何 View 的布局。例如,查看 Views 文件夹中的 _ViewStart.cshtml 文件:
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
这基本上告诉所有 Controller 使用该布局作为 Controller 操作返回的 View 的包装器。
您的 _Layout.cshtml 文件已经提示了一种用值填充它的方法:
<head>
...
<title>@ViewBag.Title</title>
...
</head>
如果您在 View 中执行以下操作,它将呈现在 _Layout.cshtml 文件的 head/title 部分:
@{
@ViewBag.Title = "Home";
}
关于asp.net-mvc - MVC 4 : Create controller for Shared view _Layout. cshtml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14160995/