how to get the id from /controller/action/id from within a view page?
From inside a viewpage, how can I r开发者_运维技巧eference the id from the url /controller/action/id without getting this data from the model?
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.
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"] %>
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
精彩评论