简体   繁体   中英

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

在一个视图页面中,如何从url / controller / action / id中引用ID,而又不从模型中获取此数据?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM