asp.net-mvc 如何在视图中获取路由值(Asp.net Mvc)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17699082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 03:01:48  来源:igfitidea点击:

How to get a route value in the view (Asp.net Mvc)

asp.net-mvcasp.net-mvc-4

提问by Daniel Ezra

Is there an alternative to get the route value in the view page instead of read it like querystring ?

是否有替代方法可以在视图页面中获取路由值而不是像 querystring 那样读取它?

@Html.ActionLink("Language Resources", "Index", "LanguageResource", 
                 new { languageCode = Request.QueryString["languageCode"] , "")

采纳答案by Ruben Bartelink

Don't rule out keeping it simple:

不排除保持简单:

public ActionResult Action(int id)
{
    return View( id);
}

Indicate the type of the Model we're dealing with

表明我们正在处理的模型的类型

@model int 

And refer to the value in a strongly typed way via:

并通过以下方式以强类型方式引用该值:

@Model

回答by Amit

try to find from below code

尝试从下面的代码中找到

In Razor

在剃刀

@{
    var id = ViewContext.RouteData.Values["id"];
 }

In WebForms:

在 WebForms 中:

<% 
    var id = ViewContext.RouteData.Values["id"];
%>

回答by maxs87

You can use RequestContext

您可以使用 RequestContext

@{
var id = HttpContext.Current.Request.RequestContext.RouteData.Values["id"];
}

回答by user3777549

And for the less experienced out there, you can access the controller and the action parts of the URL too. (Razor Example)

对于经验不足的人,您也可以访问控制器和 URL 的操作部分。(剃刀示例)

if(ViewContext.RouteData.Values["action"].ToString() == "Account")
{
    @Html.Raw("Hi ") @Session["UserName"]
}

Where,

在哪里,

context.MapRoute(
            name: "MyRoute",
            url: "{controller}/{action}/{id}"
}