部分视图中的MVC TempData值错误
本文关键字:TempData 错误 MVC 视图 | 更新日期: 2023-09-27 17:52:54
我定义了以下常量:
namespace MyProject.Constants
{
public static class AppConstants
{
// View Bag / Temp Data Constants
public const string CurrentAction = "CurrentAction";
public const string CurrentController = "CurrentController";
}
}
In my _layout。我将它们设置如下:
@using MyProject.Constants
@{
TempData[AppConstants.CurrentAction] = ViewContext.RouteData.GetRequiredString("action").ToLower();
TempData[AppConstants.CurrentController] = ViewContext.RouteData.GetRequiredString("controller").ToLower();
}
<!DOCTYPE html>
<html>
...
<body>
@Html.Partial("_SubNavigation")
</body>
</html>
但是我无法访问我的_SubNavigation中的TempData。CSHTML局部视图:
<li><a href="@Url.Action("Index", "Home")" class="@(TempData[AppConstants.CurrentController].ToString() == "home" && TempData[AppConstants.CurrentAction].ToString() == "index" ? "active" : "")">Home</a></li>
我得到错误The name 'AppConstants' does not exist in the current context
如果我直接在部分中添加以下代码片段,那么它可以工作吗?
@using MyProject.Constants
@{
TempData[AppConstants.CurrentAction] = ViewContext.RouteData.GetRequiredString("action").ToLower();
TempData[AppConstants.CurrentController] = ViewContext.RouteData.GetRequiredString("controller").ToLower();
}
如果没有引用的代码片段,部分视图是否以 开头?我得到错误名称'AppConstants'在当前上下文中不存在
@using MyProject.Constants
?
在引用该名称空间中的名称的每个视图以及您需要的任何其他名称空间中都需要这样做。如果您需要的名称空间在视图中占很大比例,请考虑将其添加到views文件夹中的web.config
文件中的全局名称空间列表中。