How to get the current route identifier in a view from a URL (ASP.NET MVC)

In a view that returns from a URL such as / Controller / Action / 1 (if the default route of the controller is / action / id), how can I access the identifier from the view?

I do not want to add it to the ViewData dictionary at the action level when processing the request.

+76
asp.net-mvc
Jun 11 '09 at 5:46
source share
8 answers

I think this is what you are looking for:

<%=Url.RequestContext.RouteData.Values["id"]%> 
+176
Jul 21 '09 at 16:55
source share

ViewData is exactly what you need to do.

Another option is to pass the model containing the ID to the view.

Edit: Not knowing exactly what you are linking, it is difficult to give more specific recommendations. Why do you need an identifier, but not any other model data? Is your controller really just sending the Id field to the view? It is hard to imagine what a scenario is.

If the ID value is really the only model information that is passed to your view, then you can use the ID itself as a model. Then the return value of your action method will be View(id) , and you will not need to use ViewData.

+15
Jun 11 '09 at 6:00
source share

Adding it to viewdata is the right thing. As for how to add it, you can always add a custom ActionFilter that grabs it from the route dictionary and pops it into viewdata.

+3
Jun 11 '09 at 14:43
source share

I think you can directly use the url Url.RequestContext.RouteData.Values ​​["ID"] in action

+2
04 Oct '17 at 6:58
source share

We can pass id as Route Data or QueryString , therefore, to support both of them , I recommend this method:

 var routeValues=Url.RequestContext.RouteData.Values; var paramName = "id"; var id = routeValues.ContainsKey(paramName)? routeValues[paramName]: Request.QueryString[paramName]; 
+1
06 Sep '16 at 23:47
source share

Just my two cents, but I always use presentation models to pass any data into my views. Even if it is as simple as int as id.

This makes access to this value trivial, since MVC does all the work for you.

For what it's worth, I usually call my view models like this:

{Controller}{ViewName}ViewModel

This helps to keep things to scale.

Example:

 // ~/ViewModels/HomeEditViewModel.cs public class HomeEditViewModel { public int Id { get; set; } } // ~/Controllers/HomeController.cs public IActionResult Edit(int id) { return View(new HomeEditViewModel() { Id = id }); } // ~/Views/Home/Edit.cshtml @model HomeEditViewModel <h1>Id: @Model.Id</h1> 
+1
Feb 15 '18 at 2:59
source share

A simple answer in a razor:

 @Url.RequestContext.RouteData.Values["id"] 
0
Jun 07 '19 at 14:31 on
source share

I just used <%= model.id %> and it works

-one
Feb 10 '14 at 11:26
source share



All Articles