Reputation: 2193
Within the view that is returned from a URL such as /Controller/Action/1 (assuming the default route of controller/action/id), how can I get access to the ID from within the View?
I don't want to have to add it to the ViewData dictionary at the action level when handling the request.
Upvotes: 79
Views: 70133
Reputation: 5157
Simple Answer In Razor:
@Url.RequestContext.RouteData.Values["id"]
In ASP.NET Core
@Url.ActionContext.RouteData.Values["id"]
Upvotes: 3
Reputation: 31
If you are using .NET Core
Use this code
Url.ActionContext.RouteData.Values["id"]
Upvotes: 3
Reputation: 12587
Just my two cents, but I always use view models for passing any data to my views. Even if it's as simple as needing an int
like the id.
Doing this makes accessing this value trivial, as MVC does all the work for you.
For what it's worth I typically name my view models as such:
{Controller}{ViewName}ViewModel
This helps keeps things organized at scale.
An 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>
Upvotes: 1
Reputation: 334
I think you can direct use in url action Url.RequestContext.RouteData.Values["id"]
Upvotes: 2
Reputation: 17425
We can pass id
as Route Data
or QueryString
, so to support both of them i recommend this way:
var routeValues=Url.RequestContext.RouteData.Values;
var paramName = "id";
var id = routeValues.ContainsKey(paramName)?
routeValues[paramName]:
Request.QueryString[paramName];
Upvotes: 2
Reputation: 4101
I think this is what you're looking for:
<%=Url.RequestContext.RouteData.Values["id"]%>
Upvotes: 184
Reputation: 15663
Adding it to the viewdata is the right thing to do. As for how to add it, you could always add a custom ActionFilter
which grabs it from the route dictionary and pushes it into the viewdata.
Upvotes: 3
Reputation: 13837
ViewData is exactly the right way of doing this.
Your other option would be to pass a model that contains ID to the view.
Edit: Without knowing exactly what you're tying to do, it's tough to give more specific advise. Why do you need an ID, but not any other model data? Is your controller really only sending the Id field to the view? It's hard to imagine what the scenario is.
If the ID value is truly the only model information that is being passed to your view, then you could use the ID itself as the model. Then the return value of your action method would be View(id)
and you wouldn't need to use ViewData.
Upvotes: 16