[英]ASP.NET MVC5 Access ViewBag from layout?
我目前正在尝试将动态数据从我的控制器传递到我的视图和布局。 我目前正在使用 ViewBag 将数据从控制器传递到工作正常的视图。 我无法从布局中访问 ViewBag。 有没有办法做到这一点?
我正在使用 ASP.NET W/MVC5 (C#)。
编辑:更新 W/ 代码:
//layout.cshtml
@ViewBag.username
产生这个错误:
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0103: The name 'ViewBag' does not exist in the current context
我建议你有一个动作方法,布局使用它来传递你需要的数据。 例如
public class ControllerName : Controller
{
public ActionMethod GetData()
{
return Content("Some data"); // Of whatever you need to return.
}
}
然后在布局和视图中你可以调用
@Html.Action("GetData", "ControllerName")
一种简单的方法是从您的视图中设置一个 ViewBag 属性,然后该属性将在您的布局文件中可用
索引.cshtml
@{
ViewBag.Container = false;
}
_Layout.cshtml
@{
var container = ViewBag.Container != null && !ViewBag.Container ? "" : "container";
}
<div class="@container">
...
</div>
考虑 AppController 控制器中的一个 Action,它返回 Index.cshtml 视图:
public class AppController: Controller
{
public IActionResult Index()
{
ViewBag.Title = "Home Page";
return View();
}
}
在我的 Index.cshtml 视图中,我可以直接调用@ViewBag.Title来获取我之前在操作中设置的内容。
<head>
<meta charset="UTF-8" />
<title>@ViewBag.Title | Example.com</title>
<link href="css/site.css" rel="stylesheet" type="text/css" />
</head>
您甚至可以传递像列表这样的复杂数据,并使用 Razor 的模型/模型访问视图中的数据。
我希望我能帮助你回答这个问题。
只需在您的家庭控制器中使用视图包,您也可以在布局页面上访问它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.