Blankman
Blankman

Reputation: 267390

how to get the id from /controller/action/id from within a view page?

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

Upvotes: 2

Views: 2210

Answers (3)

stack72
stack72

Reputation: 8288

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

Upvotes: -1

Jaco Pretorius
Jaco Pretorius

Reputation: 24830

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"] %>

Upvotes: 0

mathieu
mathieu

Reputation: 31202

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.

Upvotes: 9

Related Questions