tags:

views:

1043

answers:

3

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.

+3  A: 

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.

Dennis Palmer
Unfortunately the View doesn't have a model.Something about `ViewData["id"] = id;` just doesn't sit right with me. I guess it's the fact that I am using this pattern quite a few times. Once or twice and I probably wouldn't mind.Thanks.
JMs
+2  A: 

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.

Wyatt Barnett
I like that idea, with proper null value checking you would just put that at the top of your controller and you should be able to always rely on it being there when it's supposed to be.
dhulk
Or just make a nice little ViewDataWrapper class that could manage the "what to do if this is null" stuff for ya . . .
Wyatt Barnett
Awesome idea, thanks!
JMs
+12  A: 

I think this is what you're looking for:

<%=Url.RequestContext.RouteData.Values["id"]%>
Francisco