![](/img/trans.png)
[英]ASP.NET MVC 5 routing - create Html.ActionLink and parse ViewContext.RouteData.Values
[英]ViewContext.RouteData.Values["Controller"] always Null - Asp.Net Core 2.1
我從使用 Asp.Net Core 2.1 作為起點的標准 ASP.NET Core Web 應用程序模板開始。
然后我在共享文件夾中添加了一個左側導航面板,如下所示: ActiveRouteTagHelper
在這個導航面板中,我想突出顯示活動鏈接,我使用了以下解決方案: Ben Cull's ActiveRouteTagHelper for MVC 。
然后我遇到了以下問題:
當我點擊調試並且應用程序啟動時,我希望在ViewContext.RouteData.Values["Controller"]
看到控制器值。
對於第一次和每隔一次點擊,即使可以看到Url顯示了正確的操作和控制器名稱
private bool ShouldBeActive()
{
try
{
var currentController = ViewContext.RouteData.Values["Controller"].ToString();
var currentAction = ViewContext.RouteData.Values["Action"].ToString();
}
catch (Exception ex)
{
return false;
}
}
為清楚起見,我刪除了該方法的其余部分。
我的Startup
班:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(_configuration);
services.Configure<AppSettings>(_configuration.GetSection("PortalSettings"));
var settings = _configuration.Get<AppSettings>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddMvc();
services.AddMvc().AddControllersAsServices();
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
// If this is the case then enable more detailed error output
app.UseDeveloperExceptionPage();
// Display a more specific error page when an exception occurs connecting to the database
app.UseDatabaseErrorPage();
}
else
{
// If this is not the case then forward the error to our generic view
app.UseExceptionHandler("/Shared/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute("default", "{controller}/{action}/{id?}");
});
app.UseAuthentication();
}
我的問題是,我如何得到這兩行返回一個值? 因為無論我嘗試過什么都證明是成功的。 結果總是為空!!
var currentController = ViewContext.RouteData.Values["Controller"].ToString();
var currentAction = ViewContext.RouteData.Values["Action"].ToString();
我嘗試了各種路由映射選項,但都無濟於事。 有任何想法嗎?
您混淆了 Razor Pages 和 MVC。 ASP.NET Core 的默認 Web 應用程序模板為您提供了一個 Razor Pages 應用程序 ( https://www.learnrazorpages.com ),根據您發布的圖片,這就是您所擁有的。
Razor Pages 中的路由是根據 Pages 文件夾中內容的文件路徑定義的,而不是控制器和動作方法。 如果需要 MVC 應用程序,請選擇ASP.NET Core Web Application作為項目類型,然后選擇Web Application (Model-View-Controller) 。
我不知道這是否是正確的方法,但我發現這篇博客文章展示了如何使該標簽助手與 Razor Pages 一起工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.