views:

48

answers:

3

From inside a viewpage, how can I reference the id from the url /controller/action/id without getting this data from the model?

A: 

you can pass the id into the view via the ViewData -

ViewData["id"] = id;

Then in the view you can call this ViewData["id"] to pull the value you out

paul

PaulStack
i love how i got a down vote for this answer yet the answer above me is exactly the same and didnt get a down vote. I dont mind down votes but give a reason so that i can learn from it
PaulStack
I didn't downvote - but I'd imagine it to be because you haven't assign anything to `id`.
David Neale
A: 

You can use the RouteData, but you shouldn't.

The whole structure of MVC says that a request will be routed to a specific action on a specific controller. The controller will then return a view and the view no longer accesses the url parameters.

If you want to access the id you should put it into the view model or view data and access that in the view.

public ActionResult YourAction(int id)
{
    ViewData["id"] = id;

    return View("MyView");
}

and then in the view...

<%= ViewData["id"] %>
Jaco Pretorius
"You can't." : wrong, you can access it using the ViewContext.RouteData. But it's a bit smelly :)
mathieu
Yeah ok, but you definitely shouldn't.
Jaco Pretorius
+5  A: 

You can try the viewContext :

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

You still could get it via ViewData["id"], if you put it inside viewdata in the controller, but if you do this, you might as well put it in the model.

You really should get it from the model, as previous options seems like a code smell to me.

mathieu
+1 for code smell
Jaco Pretorius