How to find out the current resource and controller name from the view in ASP.NET MVC
I'm using the ASP.NET MVC in a RESTful resource manner and I want to be able get the current resource and controller name from the view.
I'm attempt to create a HTML page and I want to kn开发者_如何学运维ow the current resource and controller name is it possible to get this?
you can get that in a view by looking at the ViewContext.Controller property. The ViewContext property also gives access to many other useful properties such as Route Data, Application, Cache, ViewData, etc.
EDIT: To get the actual name of the controller you can go one of two ways:
1) Call GetType() on the Controller property of ViewContext and use that Name property to get the class name of the controller
2) Look at the route data and examine the values for the "controller" key, e.g. ViewContext.RouteData.Values["controller"] (this would likely be the preferred method)
This information is available in the ViewContext
property of ViewPage
(assuming you are using .aspx
for your views).
You can always run GetType while in the controller (or just type it in if thats what you want to do) and store it in the view data. If you are using the same view from multiple controllers, you might want to make it a strongly typed view and have the controller name be part of it.
Can you be more specific with why exactly you want to do this? There might be a better way.
精彩评论