如何在ASP.NET MVC视图中访问路由参数?

时间:2021-04-21 04:09:06

I have an URL like this /home/action/id

我有一个像这样的/ home / action / id的URL

How can I access this id in view?

如何在视图中访问此ID?

2 个解决方案

#1


38  

This should work in your view:

这应该在您的视图中工作:

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

(assuming the route parameter is named "id")

(假设路由参数名为“id”)

#2


10  

you can pass it in through viewData;

你可以通过viewData传入它;

In your Controller:

在您的控制器中:

public ActionResult Index(string id)
{
    ViewData["Name"] = Server.UrlEncode(id);
    return View();
}

In your View:

在您的视图中:

<h1><%= ViewData["Name"] %></h1>

#1


38  

This should work in your view:

这应该在您的视图中工作:

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

(assuming the route parameter is named "id")

(假设路由参数名为“id”)

#2


10  

you can pass it in through viewData;

你可以通过viewData传入它;

In your Controller:

在您的控制器中:

public ActionResult Index(string id)
{
    ViewData["Name"] = Server.UrlEncode(id);
    return View();
}

In your View:

在您的视图中:

<h1><%= ViewData["Name"] %></h1>